今天看到这么一个题
根据下列代码写出运行结果。
public class ExtendsExercise02 {
public static void main(String[] args) {
C c = new C();
}
}
class A {//A 类
public A() {
System.out.println("我是 A 类");
}
}
class B extends A { //B 类,继承 A 类 //main 方法中: C c =new C(); 输出么内容? 3min
public B() {
System.out.println("我是 B 类的无参构造");
}
public B(String name) {
System.out.println(name + "我是 B 类的有参构造");
}
}
class C extends B { //C 类,继承 B 类
public C() {
//this("hello")会指向c的有参构造
this("hello");
System.out.println("我是 c 类的无参构造");
}
public C(String name) {
super("hahah");
System.out.println("我是 c 类的有参构造");
}
}
大家可以先写写。
输出结果
我是 A 类
hahah我是 B 类的有参构造
我是 c 类的有参构造
我是 c 类的无参构造
而我想的是
我是 A 类
我是 B 类的无参构造
我是 c 类的无参构造
(太久没看Java了,最基础的都忘了,哎!)
为什么会有?
hahah我是 B 类的有参构造
因为this(“hello”)调用了c类的有参构造,所以执行了c类有参构造器。