0

how (((GrandParent)this).x)) able to print value of x of GP class, how after inheritance object is created in heap. how it store grandparent nd parent data .

class GrandParent
{
        int x = 34;
}

class Parent extends GrandParent
{
        int x =87;
}

class Child extends Parent
{
    int x =536;
    void show()
    {
        System.out.println("value of local x "+x);
        System.out.println("value of Parent x "+super.x);
       System.out.println("value of GrandParent x "+(((GrandParent)this).x));
    }
    public static void main(String... s)
    {
        Child c1 = new Child();
        c1.show();
    }
}

output

value of local x 536

value of Parent x 87

value of GrandParent x 34
HitRo
  • 1
  • 3
  • 2
    Are you saying it outputs the wrong value? What is the question? – tinonetic Sep 06 '16 at 13:27
  • What language is this. [tag:java]? – deceze Sep 06 '16 at 15:12
  • it run correctly , i dont understand how it worked , how (((GrandParent)this).x)) able to print value of x of grandparent class, how after inheritance object is created in buffer. how it store grandparent nd parent data memeber . and deceze this is a java program – HitRo Sep 06 '16 at 16:03
  • 1
    answer is found at this question: http://stackoverflow.com/questions/9414990/if-you-overwrite-a-field-in-a-subclass-of-a-class-the-subclass-has-two-fields-w – Jeutnarg Sep 06 '16 at 19:45
  • Jeutnarg , i know with help of casting we can access hidden data member . but i want to know its internal working and object design in buffer after inheritance . i want to know what happen when we typecast this , since it print same reference id whether it is typecast by other class . sorry i am new at java ,but i want to know how it works ,and its internal structure of working . i couldn't find in books so asked here – HitRo Sep 07 '16 at 06:39

0 Answers0