Casting to parent type -- Java
casting, inheritance, java
Solution
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.
Problem
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.