简体   繁体   中英

How type-casting works in java to access parent's member?

class Grand {
    int x = 10;
}

class Parent extends Grand{
    int x = 20;
}

class Childs extends Parent{
    int x = 30;
    void show(){
    System.out.println(this.x);
    System.out.println(super.x);  //accessing parent's member
    System.out.println((Grand)this.x);   //why type-casting
}

I know that using the super keyword in Java, we can access parent method/member which gets hidden/overriden by child method/member.

But in multi-level inheritance, we access parent's parent method using typecasting child's object.

How does type-casting work internally to access the super's parent class member. Is there any other way around to do this?

Can we access the methods similarly using typecasting?

You need to cast because instance fields do not get overridden (like methods do).

When you redeclare a field of the parent in a child class, you are hiding the parent's field.

And when a field is hidden, you use a reference of the parent type to read the value of the parent field:

So either of these is needed to read the field of Grand :

((Grand)this).x

Or:

Grand grand = this
int val = grand.x //reads parent's x

This hopefully makes it clear that hiding fields is a bad idea.

To make story short, with great simplification, objects in memory are represented as pointers to the area which contains all their field members (unique area copy for each object instance) and table/area which contain pointers to member functions (one per class, same for all objects).

In Java all function-members are virtual, so overriding function member you override the cell in virtual methods memory table. So virtual basically means able to be overridden. And there is also special pointer, called 'super', which points to the virtual methods table of parent class. So you can access this table by 'super' keyword.

If you declare field-members in ancestors, you expand the parent object instance area, ie all ancestors fields in memory goes after parent ones. But as you use same names for both, this creates ambiguity, so compiler warns you are "hiding" members. They are not overridden, as functions, they are still there, but compiler choose actual field to access as the one which is declared in the class, depending on the pointer type you use. If you don't specify any pointer, this implicitly treated as "this", and the type would be ancestor, ie ancestor's field. To access the parent class field, you need to cast (this) pointer to parent class, so compiler will choose field of the parent class you hide in ancestor.

The difference here is because all objects of the same class use same methods, but values of fields are not shared between object instances.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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