Search code examples
javaderived-class

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.


Solution

  • 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
    }