一、研究问题
1.子类如何继承父类的构造器?
2.子类与父类构造器执行顺序?
二、创建父类
创建父类Animal,有两个构造器
class Animal{ private Integer high; public Animal() { System.out.println("Animal()"); } public Animal(Integer high) { System.out.println("Animal(Integer high)"); this.high = high; } // set、get方法 public Integer getHigh() { return high; } public void setHigh(Integer high) { this.high = high; } }
三、创建子类
创建子类Dog,继承Animal,有四个构造器
class Dog extends Animal{ private String name; public Dog() { System.out.println("Dog()"); } public Dog(String name) { this.name = name; System.out.println("Dog(String name)"); } public Dog(Integer high) { super(high); System.out.println("Dog(Integer high)"); } public Dog(Integer high, String name) { super(high); this.name = name; System.out.println("Dog(Integer high, String name)"); } // set、get方法 public String getName() { return name; } public void setName(String name) { this.name = name; } }
四、调用子类构造器
public class MyMain { public static void main(String[] args) { System.out.println("- - - - - - - new Dog() - - - - - - -"); Dog dog = new Dog(); System.out.println("- - - - - - - new Dog(Integer high) - - - - - - -"); Dog highDog = new Dog(180); System.out.println("- - - - - - - new Dog(String name) - - - - - - -"); Dog nameDog = new Dog("张二狗"); System.out.println("- - - - - - - new Dog(Integer high, String name) - - - - - - -"); Dog highNameDog = new Dog(180,"张二狗"); } }
五、输出结果
- - - - - - - new Dog() - - - - - - - Animal() Dog() - - - - - - - new Dog(Integer high) - - - - - - - Animal(Integer high) Dog(Integer high) - - - - - - - new Dog(String name) - - - - - - - Animal() Dog(String name) - - - - - - - new Dog(Integer high, String name) - - - - - - - Animal(Integer high) Dog(Integer high, String name)
六、结论
1.子类通过super调用父类构造器
子类通过super()调用父类无参构造器;通过super(参数)调用父类有参构造器;如果不写super,子类默认调用父
类无参构造器
2.子类创建对象时,父类构造器会先执行。
因为在构造器中super必须放在第一个执行,否则会报错