在派生类上禁用继承的方法 [英] Disabling inherited method on derived class
问题描述
在Java派生类中,有没有办法禁用从基类继承的方法和/或字段?
Is there any way to, in a Java derived class, "disable" a method and/or field that is otherwise inherited from a base class?
例如,假设你有一个 Shape
基类,它有一个 rotate()
方法。您还有从 Shape
类派生的各种类型: Square
, Circle
, UpwardArrow
等。
For example, say you have a Shape
base class that has a rotate()
method. You also have various types derived from the Shape
class: Square
, Circle
, UpwardArrow
, etc.
形状
有一个 rotate()
方法。但我不希望 rotate()
可供 Circle
的用户使用,因为它没有意义,或者是用户 UpwardArrow
,因为我不希望 UpwardArrow
能够旋转。
Shape
has a rotate()
method. But I don't want rotate()
to be available to the users of Circle
, because it's pointless, or users of UpwardArrow
, because I don't want UpwardArrow
to be able to rotate.
推荐答案
我认为不可能。
但是你可以通过从其规范中删除rotate()方法来进一步细化 Shape 类,而是定义另一个子类的Shape称为 RotatableShape ,让来自 Shape 的 Circle derive 以及 RotatableShape 中的所有其他可旋转类 。
I don't think it is possible. However you can further refine the Shape class by removing the rotate() method from its specification and instead define another subclass of Shape called RotatableShape and let Circle derive from Shape and all other Rotatable classes from RotatableShape.
例如:
public class Shape{
//all the generic methods except rotate()
}
public class RotatableShape extends Shape{
public void rotate(){
//Some Code here...
}
}
public class Circle extends Shape{
//Your implementation specific to Circle
}
public class Rectangle extends RotatableShape{
//Your implementation specific to Rectangle
}
这篇关于在派生类上禁用继承的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!