java----super关键字使用

java中的super关键字是一个引用变量,用于引用直接父类对象。

每当创建子类的实例时,父类的实例被隐式创建,由super关键字引用变量引用。

使用一:super用于引用直接父类实例变量

可以使用super关键字来访问父类的数据成员。 如果父类和子类具有相同的数据成员,则使用super来指定为父类数据成员。

class Animal {
    String color = "red";
}

class Dog extends Animal {
    String color = "yellow";

    void printColor() {
        System.out.println(color);
        System.out.println(super.color);
    }
}

class TestSuper1 {
    public static void main(String args[]) {
        Dog d = new Dog();
        d.printColor();
    }
}
执行结果:yellow red

使用二: 通过 super 来调用父类方法

super关键字也可以用于调用父类方法。 如果子类包含与父类相同的方法,则应使用super关键字指定父类的方法。

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();
    }
}

class TestSuper2 {
    public static void main(String args[]) {
        Dog d = new Dog();
        d.work();
    }
}
结果:eating... barking...

使用三: 使用 super 来调用父类构造函数

super关键字也可以用于调用父类构造函数。

class Person {
    int id;
    String name;

    Person(int id, String name) {
        this.id = id;
        this.name = name;
    }
}

class Emp extends Person {
    float salary;

    Emp(int id, String name, float salary) {
        super(id, name);
        this.salary = salary;
    }

    void display() {
        System.out.println(id + " " + name + " " + salary);
    }
}

class TestSuper5 {
    public static void main(String[] args) {
        Emp e1 = new Emp(1, "ankit", 45000f);
        e1.display();
    }
}

Emp类继承了Person类,所以Person的所有属性都将默认继承到Emp。 要初始化所有的属性,可使用子类的父类构造函数。 这样,我们重用了父类的构造函数。

结果:1 ankit 45000
经验分享 程序员 微信小程序 职场和发展