简体   繁体   English

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

[英]Why output of following code is x=0 x=20?

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();

        }

}

You get 0 because that is the default value of an int , and your constructor hasn't yet run . 您得到0是因为这是一个int的默认值,并且您的构造器尚未运行 You are also shadowing your variable x in Child . 您还将在Child隐藏变量x Further, there isn't an implicit super invocation for anything except constructors. 此外,除了构造函数外,没有任何隐式的super调用。 I think you wanted / expected something like, 我认为您想要/期望类似的东西,

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);
    }
}

With those changes I get 有了这些变化,我得到了

x = 10 x = 20 

Note that the Override annotation is optional (but a good practice when you override an implementation). 请注意, Override注释是可选的(但重写实现时是一种好的做法)。

Parent p = new Child();

Will call the constructor in the parent. 将在父级中调用构造函数。

The constructor in the parent calls the method foo() The method foo() is in both the class Parent and Child 父级中的构造函数调用方法foo()方法foo()同时在ParentChild类中

Since you have instantiated the Child class, the method call foo() in the parent calls the method foo() in the child class. 由于您已实例化Child类,因此父级中的方法foo()调用子级中的方法foo()

After you call p.foo() , x is assigned to 20 While the child class is still not instantiated which has an undeclared integer x which prints 0 . 调用p.foo() ,x分配给20,而子类仍未实例化,该子类具有未声明的整数x ,其输出0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM