子类继承父类

来源:互联网 发布:多媒体网络中控系统 编辑:程序博客网 时间:2024/05/21 21:49

父类:

public class Father {
public int i = 0;


Father() {
System.out.println(i);
}


Father(int i) {
this.i = i;
System.out.println(i);
}


protected void output() {
System.out.println(this.i);
}


public void add() {
this.i++;
}
}

子类

public class Son extends Father {
Son() {
// 当实例化子类时,会先实例化父类,先调用父类的构造方法
// 父类有构造方法时,必须调用,
// 父类的无参构造方法会自动调用,要调用有参构造方法时用super(参数)


super(10); // 不能在静态方法中使用


add();
output();


}


public static void main(String[] args) {


Son son = new Son();
son.add();
son.output();
}


}


运行结果:

10

11

12

注释掉super(10)的运行结果为:

0

1

2