简体   繁体   中英

Casting to parent type — Java

This rather is a verification:

Is there any gain in casting a child object to a parent type?

Suppose I have the two classes Parent and Child . Child is extending Parent .

Is there any difference in the code

Parent p = new Child();

and

Parent p = (Parent) new Child();

?

Would p behave any differently on invoking any of its methods or accessing any one of its members in any way?

From my end, the two are the same and casting here is redundant.

//==================================

EDIT: I've been looking to have control, as the developer, on which method to call-- the method of Child or Parent , from outside Child .

So, the coder will look to invoke the method of Parent regardless of whether that method is overridden in the subclass. That is, the overridden method of the subclass will be by-passed, and the Parent implementation of that method will be invoked on the Child object.

No, the object would behave the same regardless of the type of reference through which you call the method.

This is by design - it allows subclasses to override methods of their superclasses.

In your example, the upcast before assignment has no effect - it will happen implicitly as part of the assignment.

Parent p = (Parent) new Child();

The caller can't force an object to ignore its method overrides. This is a good thing. Otherwise, a child could never enforce its own internal invariants.

If you want to allow the caller to choose whether to call the parent method or the child method, then your API can provide two methods . Both the parent and the child can determine how to support each.

To answer your second question: this is impossible by design. There is no way to call a parent method if it is overridden by the child except from code in the child. If the child wants to allow this, you can provide another method which uses super to invoke the overridden parent method. Of course the second method would need to have a different name.

It's called Polymorphism. If the childs overrides a method there will always be the child implemetation called. No matter of what type your variable is. Casting is only needed for the other way around - if you want to call Child Methods on an Object where you know that its of type Child, but the Variable is declared as Partent. But its usually bad style to cast variables ( there are exceptions to that - like the equals method)

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