Java的super关键字

1. 什么是超级关键词?
shì cí?)

这是一个引用超类(父类)对象的关键字。

2,源代码

public class Main {

    public static void main(String[] args) {

        // super = keyword refers to the superclass (parent) of an object
        //         very similar to the "this" keyword

        Hero hero1 = new Hero("Batman", 42, "$$$");
        Hero hero2 = new Hero("Superman", 43, "everything");

        System.out.println(hero1.name);
        System.out.println(hero1.age);
        System.out.println(hero1.power);

        System.out.println(hero2.toString());

    }

}

类Person(超类)?

public class Person {

    String name;
    int age;

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

    public String toString() {
        return this.name + "\n" + this.age + "\n";
    }

}

继承自Person类的Hero类?

public class Hero extends Person {

    String power;

    public Hero(String name, int age, String power) {
        super(name, age);

        this.power = power;
    }

    public String toString() {
        return super.toString() + this.power;
    }
}
广告
将在 10 秒后关闭
bannerAds