构造函数和抽象类中的java调用方法?
//输出为构造函数和抽象类中的java调用方法?,java,constructor,Java,Constructor,//输出为 public class NewSeqTest { public static void main(String[] args) { new S(); new Derived(100); } } class P { String s = "parent"; public P() { test(); } public void test() { //test 1 System.out.println(s + " parent
public class NewSeqTest {
public static void main(String[] args) {
new S();
new Derived(100);
}
}
class P {
String s = "parent";
public P() {
test();
}
public void test() { //test 1
System.out.println(s + " parent");
}
}
class S extends P {
String s = "son";
public S() {
test();
}
@Override
public void test() { //test 2
System.out.println(s + " son");
}
}
abstract class Base {
public Base() {
print();
}
abstract public void print();
}
class Derived extends Base {
private int x = 3;
public Derived(int x) {
this.x = x;
}
@Override
public void print() {
System.out.println(x);
}
}
我的问题是1.为什么P构造函数打印“空子”;我认为是“空父母” 2为什么抽象类基类可以在构造函数中执行抽象方法print() 对不起,代码格式,我不知道如何正确使用它
S
中重写了方法test
,并且正在构造类型为S
的对象。因此,在超类构造函数中,当调用test()
时,它会从子类S
调用被覆盖的test()
。这是压倒一切的关键print
在类Derived
中不是抽象的,您正在Derived
的实例中构造,而不是Base
的实例。(由于您提到的原因,说newbase()
是非法的:您不能调用抽象方法)news()代码>导致P
构造函数运行test()
。它执行S
中覆盖的test()
,该测试打印S
。它在s
中使用s
,由于s
的构造函数是在P
的构造函数之后执行的,因此尚未初始化s
2.答案与1相同。已执行重写的print()
,但尚未初始化x
李>
顺便说一句:尝试使用调试器并逐步运行程序,以遵循执行路径
null son
son son
0