为什么以下代码的输出是x = 0 x = 20?

时间:2018-02-20 05:36:33

标签: java variables override

class Parent 

{

protected int x = 10;

public Parent() 

{

    foo();
    }
    public void foo()
    {
         System.out.printf("x = %d ", x);
    }
}

class Child extends Parent 

{

private int x = 20;

public void foo() 

{

    System.out.printf("x = %d ", x);

    }

}
public class Main

{

    public static void main(String[] args)

    {

        Parent p=new Child();

        p.foo();

        }

}

2 个答案:

答案 0 :(得分:0)

您获得0,因为这是int的默认值,而您的构造函数尚未运行。您还在x中隐藏变量Child。此外,除了构造函数之外,没有任何隐式super调用。我想你想要/想要的东西,

public class Parent {
    private int x = 10; // <-- this also works if protected

    public void foo() {
        System.out.printf("x = %d ", x);        
    }
}

public class Child extends Parent {
    private int x = 20;

    @Override
    public void foo() {
        super.foo();
        System.out.printf("x = %d ", x);
    }
}

我得到了这些改变

x = 10 x = 20 

请注意,Override注释是可选的(但是当覆盖实现时,这是一个很好的做法)。

答案 1 :(得分:0)

Parent p = new Child();

将调用父项中的构造函数。

父级中的构造函数调用方法foo() 方法foo()同时属于

由于您已实例化Child类,因此父级中的方法调用foo()将调用子类中的方法foo()

致电p.foo()后,x被分配到 20 虽然子类仍未实例化,其中有未声明的整数x ,其打印 0