Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disabling inherited method on derived class

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.

like image 910
Jean-François Corbett Avatar asked Mar 30 '11 12:03

Jean-François Corbett


People also ask

Do derived classes override inherited methods?

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.

How do you restrict an inheritance from a 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.

Does a derived class inherit private methods?

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.

When we want to disable inheritance of class which type of class we should declare *?

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.


2 Answers

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 } 
like image 129
Chandu Avatar answered Oct 01 '22 03:10

Chandu


You can override the specific method "rotate()" in the class you want to disable this operation, like this

public void rotate() {     throw new UnsupportedOperationException(); } 
like image 45
Wavyx Avatar answered Oct 01 '22 02:10

Wavyx