Is there any way to, in a Java derived class, "disable" a method and/or field that is otherwise inherited from a base class?
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.
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.
When a base class declares a method as virtual , a derived class can override the method with its own implementation. If a base class declares a member as abstract , that method must be overridden in any non-abstract class that directly inherits from that class.
To prevent inheritance, use the keyword "final" when creating the class. The designers of the String class realized that it was not a candidate for inheritance and have prevented it from being extended.
say() because derived classes can't inherit private methods from its base class. Only protected and public methods/variables can be inherited and/or overridden.
There are 2 ways to stop or prevent inheritance in Java programming. By using final keyword with a class or by using a private constructor in a class.
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.
e.g:
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 }
You can override the specific method "rotate()" in the class you want to disable this operation, like this
public void rotate() { throw new UnsupportedOperationException(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With