Java upcast scope resolution issue
I have a base class "Shapes" and an extended class "Circle". Both have a getName method. My test class is the "Driver" class.
I upcast a Circle object to Shapes and pass it to a function called polyTest. In that function I want to call getName but I do not want the circle objects implementation of get name to be triggered but instead want the base classes implementation to be triggered.
super.getName() does not work.
My code is bellow.
public class Driver{
public static String polyTest (Shapes s){
return s.getName();
/*Instead of s.getName()... (gives me the Circle class implementation of getName() )
I want to call s.Shapes::GetName, the base class implementation of getName. */
}
public static void main(String[] args){
Circle c = new Circle();
//Test Basic inheritance & basic polymorphism.
//System.out.print(c.getName());
//Upcast test.
Shapes s = (Shapes) c;
System.out.print( polyTest(s) ); 开发者_运维知识库
}
}
public class Circle extends Shapes{
Circle(){
super();
}
public String getName(){
return "I am a Circle";
}
}
public abstract class Shapes{
Shapes (){
}
public String getName(){
return "I am a Shape";
}
}
That's just the way polymorphism Java works, I'm afraid. You can't force a virtual method call to be executed non-virtually, outside the method itself (where you can call super.getName()
). The ability to do so would break encapsulation - for example, a class may validate its arguments in a particular way in an overridden method before calling the super method... if you could get around that and say "I only want to call the original implementation" then you'd be violating the whole purpose of overriding the method in the first place.
You should redesign your code so that you don't need to call a particular implementation. The point of polymorphism is to allow subclasses to specialize behaviour without the caller knowing ahead of time what that implementation is.
Of course, if you want a method to be non-overridable, you can make it final.
- You don't need to upcast
Circle
toShapes
. (BTW, whyShapes
butCircle
?) - If you don't want your
Circle
class implement its owngetName
method, just don't override it. - If you need to override
getName
method for something else, you may want to addgetNameInSomeContext
to yourShapes
class, and override it in derived classes if necessary.
精彩评论