除了顯式調(diào)用父類的構(gòu)造方法,還有哪些方式可以初始化父類的屬性?
例如:
class Animal {? ? private String name;? ? public Animal() {? ? ? ? this.name = "無名氏";}? ? public Animal(String name) {? ? ? ? this.name = name;}? ? public String getName() {? ? ? ? return name;}}class Dog extends Animal {? ? private int age;? ? public Dog(String name, int age) {? ? ? ? super(name); // 調(diào)用父類的有參構(gòu)造方法? ? ? ? this.age = age;}? ? public void printInfo() {? ? ? ? System.out.println("名字:" + super.getName() + ",年齡:" + age);}}public class Test {? ? public static void main(String[] args) {? ? ? ? Dog dog1 = new Dog("旺財(cái)", 3);dog1.printInfo();? ? ? ? Dog dog2 = new Dog();dog2.printInfo();? ? }}
在這個(gè)示例中,Animal類中提供了一個(gè)無參構(gòu)造方法,用于初始化name屬性。在Dog類的構(gòu)造方法中,使用 super 關(guān)鍵字調(diào)用父類的有參構(gòu)造方法來初始化父類的屬性name。在main()方法中,創(chuàng)建兩個(gè)Dog對(duì)象并分別調(diào)用這些對(duì)象的printInfo()方法,輸出名字和年齡。其中,第二個(gè)Dog對(duì)象調(diào)用了父類的無參構(gòu)造方法來初始化name屬性。