构造方法在创建对象的时候是被自动调用的,然后在继承中,是先调用父类的构造方法,然后在调用子类的构造方法,
当构造方法重写之后,在super中添加对应你想要调用构造方法的参数
例:父类
package cuteSnow; public class MyFile { public int size ; public String name; public void info() { System.out.println("父类file"); } public MyFile() { System.out.println("父类构造方法1"); } public MyFile(int a) { this.size = a; System.out.println("父类构造方法2"); } }
子类
package cuteSnow; public class MyVideoFile extends MyFile{ public int duration; public MyVideoFile() { super(2); System.out.println("子类构造方法"); } }
然后正常按照创建对象走一遍
结果:
父类构造方法2
子类构造方法
这里面super(2)会识别到 public MyFile(int a) { this.size = a; System.out.println("父类构造方法2"); } 这个构造方法