Java 子对象的父引用(父对象=新子对象())

Java 子对象的父引用(父对象=新子对象()),java,inheritance,Java,Inheritance,这里ex是子对象的父引用 如果我在派生类中声明int x,输出将更改为20,20 然而,如果我不在派生类中声明x,则输出为30,4 我在想,如果我在派生类中声明x,是否会创建x的两个副本? 请帮忙 class base { public base() { x = 20; } int x = 2; public void setval() { x = 5; } } class derived extends base { int y = -1; pub

这里ex是子对象的父引用 如果我在派生类中声明int x,输出将更改为20,20
然而,如果我不在派生类中声明x,则输出为30,4 我在想,如果我在派生类中声明x,是否会创建x的两个副本? 请帮忙

class base
{

public base()
{
    x = 20;
}


int x = 2;


public void setval()
{
    x = 5;
}

}

class derived extends base
{
    int y = -1;
    public derived()
    {

        x = 30;
    }

    int x = 3;      

    public void setval()
    {

        x = 4;
    }
}

public class Inheritance {

public static void main(String[] args) {        
    base ex = new derived();
    System.out.println(ex.x);
    ex.setval();    

    System.out.println(ex.x);    

   }

 }

使用
extend
(继承)时,子级需要使用
super
来访问父级的方法和数据字段。无需在子对象中重新定义变量
x

考虑下面的代码块:

public class Derived extends Base
{
    int z;

    public Derived()
    {
        super();  // call the parent's constructor
        System.out.println(" derived constructor running");
        super.x = 30;   // access parent's data field x
    }   

    public void setVal()
    {
        System.out.println(" x value changed in derived");
        super.x = 4;
    }
}

如果我在派生类中重新定义变量,为什么会更改输出?从子类访问
x
值的正确方法是避免在子类中重新声明变量,并使用
super
访问它。在子类中从父类重新声明变量不是实现这一点的方法。这很好,但是如果我在派生类中再次声明变量,在后台会发生什么呢?任何想法都建议你阅读。此外,使用的
x
实例取决于对象类型。在您的情况下,要强制使用子实例,您的
ex
对象应该是
派生的
类型,而不是
基本的
类型。