[英]What if my subclasses have different methods too?
I have a question about polymorphism in Java.我有一个关于 Java 多态性的问题。 I have a abstract base class
Shape
and two derived classes Rectangle
and Circle
.我有一个抽象基类
Shape
和两个派生类Rectangle
和Circle
。 I know that I can call overridden methods in Circle
and Rectangle
class with a Shape
class reference but what if I have a method that Shape
class doesn't have but Circle
class has.我知道我可以使用
Shape
类引用调用Circle
和Rectangle
类中的重写方法,但是如果我有一个Shape
类没有但Circle
类有的方法怎么办。 How can I use polymorphism in this situation?在这种情况下如何使用多态?
This happens all the time.这事儿常常发生。 The answer is that you need to cast your Shape to a Circle to access the method
答案是您需要将 Shape 转换为 Circle 才能访问该方法
Shape s = ...;
if (s instanceof Circle) {
((Circle)s).foo(); //method only on Circle
}
If you store a Circle in a Shape instance, you can invoke Circle methods on s by casting s to Circle:如果将 Circle 存储在 Shape 实例中,则可以通过将 s 强制转换为 Circle 来调用 s 上的 Circle 方法:
Shape s = new Circle();
...
if ( s.instanceof(Circle) ) {
((Circle)s).circleMethod();
}
Apart from the casting solution suggested by other answers, if you think all subclasses of Shape
should provide that method but you can't/don't want to implement it on Shape
, you can declare the method as abstract and implement the method in Circle
and Rectangle
.除了其他答案建议的转换解决方案之外,如果您认为
Shape
所有子类都应该提供该方法,但您不能/不想在Shape
上实现它,则可以将该方法声明为抽象方法并在Circle
实现该方法和Rectangle
。
public abstract class Shape {
public abstract void foo();
}
public class Circle extends Shape {
public void foo() {
// Implementation
}
}
then you can do:那么你可以这样做:
Shape s = new Circle();
s.foo();
You cannot use polymorphism in this situation.在这种情况下不能使用多态。 The very idea of polymorphism is that you can use an object in a specified way irrespective of its actual shape (specific object type).
多态的本质是你可以以指定的方式使用一个对象,而不管它的实际形状(特定的对象类型)。 By requiring access to a method that is unique to (literally) a specific shape, you must forego polymorphism.
通过要求访问(字面上)特定形状所独有的方法,您必须放弃多态性。
( The above argument would not apply if Circle
actually had subclasses, in which case you could polymorphically call these methods, but this is just moving the argument somewhere else .) (如果
Circle
实际上有子类,则上述参数将不适用,在这种情况下,您可以多态地调用这些方法,但这只是将参数移到其他地方。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.