package Java;
public class Test {
public static void main(String[] args) {
//father 的默认构造器
// son 的默认构造器
father f = new son();
//father 的默认构造器
//son 的有参构造器构造器25
father f2 = new son(25);
//father 的默认构造器
//son 的默认构造器
son s = new son();
System.out.println(f.i);// 1父类的成员变量值
System.out.println(s.i);// 2 子类的成员变量值
System.out.println(son.f);// 20
}
}
/**
* InnerAdd
*/
class father {
public int i = 1;
static int f = 10;
public father() {
i = 30;
System.out.println("father 的默认构造器");
}
public father(int x) {
i = x;
System.out.println("father 的有参构造器构造器" + i);
}
}
class son extends father {
public int i = 2;
static int f = 20;
public son() {
super();
System.out.println("son 的默认构造器");
}
public son(int x) {
i = x;
System.out.println("son 的有参构造器构造器" + i);
}
}
输出:(标记在上面代码注释相应位置)
father 的默认构造器
son 的默认构造器
father 的默认构造器
son 的有参构造器构造器25
father 的默认构造器
son 的默认构造器
1
2
20
父类引用指向子类对象,子类对象构造器会首先默认调用父类的无参构造器,因此需要在父类【定义一个什么都不做的无参构造器】,否则会报错。