构造方法在创建对象的时候是被自动调用的,然后在继承中,是先调用父类的构造方法,然后在调用子类的构造方法,

当构造方法重写之后,在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"); } 这个构造方法

相关文章:

  • 2021-08-25
  • 2019-11-22
  • 2022-12-23
  • 2021-10-19
  • 2022-01-28
  • 2021-10-14
  • 2022-01-25
  • 2021-10-10
猜你喜欢
  • 2021-09-06
  • 2021-12-05
  • 2022-12-23
  • 2022-12-23
  • 2021-11-27
相关资源
相似解决方案