Disabling inherited method on derived class

后端 未结 10 1759
野趣味
野趣味 2020-12-03 06:59

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 Shap

10条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-03 07:30

    I don't think you can disable a method in the way you suggest.

    In your example, lets say you have a method that takes a Shape

    public void handleShape(Shape s){
      s.rotate();
    }
    

    Then you pass a Circle to this method

    handleShape(new Circle());
    

    What should happen? Essentially you are asking for a fundamental change to Java's type system.

    If Circle is a Shape and shouldn't be rotated then it probably means that Shape was designed poorly and shouldn't have a rotate method. You can add rotate to a different class int the hierarchy like, RotatableShape or possibly use an interface Rotatable.

提交回复
热议问题