JAVA继承——super

本文详细介绍了Java中super关键字的用法,包括调用父类的内容、构造函数以及与this关键字的区别,以及如何在子类构造函数中正确使用它们以初始化继承属性和调用父类方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.super主要的功能是完成子类调用父类中的内容,也就是调用父类中的属性或方法

2.super关键字的用法如下:

  • super可以用来引用直接父类的实例变量。
public class TestSuper1 {
    public static void main(String args[]) {
        Dog d = new Dog();
        d.printColor();
    }
}
class Animal {
    String color = "white";
}
class Dog extends Animal {
    String color = "black";
    void printColor() {
        System.out.println(color);// prints color of Dog class
        System.out.println(super.color);// prints color of Animal class
    }
}

 输出结果为

black
white
  • super可以用来调用直接父类方法。
public class TestSuper2 {
    public static void main(String args[]) {
        Dog d = new Dog();
        d.work();
    }
}
class Animal {
    void eat() {
        System.out.println("eating...");
    }
}
class Dog extends Animal {
    void eat() {
        System.out.println("eating bread...");
    }
    void bark() {
        System.out.println("barking...");
    }
    void work() {
        super.eat();
        bark();
    }
}

输出结果

eating...
barking...
  • super()可以用于调用直接父类构造函数。
public class TestSuper3 {
    public static void main(String args[]) {
        Dog d = new Dog();
    }
}
class Animal {
    Animal() {
        System.out.println("animal is created");
    }
}
class Dog extends Animal {
    Dog() {
        super();
        System.out.println("dog is created");
    }
}

输出结果

animal is created
dog is created

 注意:如果没有使用super()this(),则super()在每个类构造函数中由编译器自动添加。

(当一个子类实例化时,无论是否显式调用super()this(),最终都会执行父类的构造函数。这是因为子类的构造函数通常需要初始化继承自父类的成员变量,并且在实例化子类时,必须确保父类的构造函数得到执行以完成父类对象的初始化工作。因此,即使没有显式调用super()this(),父类构造函数内的语句最终仍然会被执行。super语句必须是子类构造函数中的第一条语句。)

3.superthis关键字的比较

super关键字:我们可以通过super关键字来实现对父类成员的访问,用来引用当前对象的父类。 this关键字:指向自己的引用。

public class TestAnimalDogDemo {
    public static void main(String[] args) {
        Animal a = new Animal();
        a.eat();
        Dog d = new Dog();
        d.eatTest();
    }
}
class Animal {
    void eat() {
        System.out.println("animal : eat");
    }
}
class Dog extends Animal {
    void eat() {
        System.out.println("dog : eat");
    }
    void eatTest() {
        this.eat(); // this 调用自己的方法
        super.eat(); // super 调用父类方法
    }
}

结果如下

animal : eat
dog : eat
animal : eat

调用父类中带参数的构造函数

super(name, age);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值