Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/372.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
构造函数和抽象类中的java调用方法?_Java_Constructor - Fatal编程技术网

构造函数和抽象类中的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()
    。这是压倒一切的关键

  • 与1相同。方法
    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