-1

here ex is parent refernce of the child object if I declare int x in derived class, the output changes to 20 , 20
however, if i dont declare x in derived class , the output is 30 , 4 i am thinking if i declare x in derived class , do 2 copies of x gets created? please help

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

   }

 }
anurag
  • 11
  • 4

1 Answers1

0

When you use extend (inheritance), the child needs to use super to access the parent's methods and data fields. There is no need to re-define the variable x in the child.

Consider the block of code below:

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;
    }
}
atomskaze
  • 101
  • 4
  • why the output gets changed if i redefine the variable in derived class? – anurag Dec 17 '19 at 15:42
  • The proper way to access the value of ```x``` from the child is to avoid re-declaring the variable in the child, and use ```super``` to access it. Re-declaring variables from the parent in the child is not the way to go about this. – atomskaze Dec 17 '19 at 15:51
  • that is fine , but what reallly happens in background if i declare variable again in derived class ? any idea – anurag Dec 17 '19 at 16:06
  • I suggest you read [Why the Instance Variable of the Super Class Is Not Overridden in the Sub Class](https://dzone.com/articles/why-instance-variable-of-super-class-is-not-overri). Also, the instance of ``x`` used depends on the object type. In your case, to force the use of the child's instance your ``ex`` object should be of type ``Derived`` rather than being of type ``Base``. – atomskaze Dec 17 '19 at 17:57