Disabling inherited method on derived class

后端 未结 10 1730
野趣味
野趣味 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:17

    One way to deal with this is to define a second method called (say) boolean isRotatable(), and use this to determine whether the rotation controls are made available to the user.

    Another option would be to introduce a Rotatable interface and use shape instanceof Rotatable to make the determination. (However, I think the isRotatable() approach is more flexible.)

    In either case, you can implement the rotate() method on a class that should never be rotated as:

    public void rotate() {
        throw new UnsupportedOperationException("rotate");
    }
    

    The Java language doesn't provide a way to "remove" or "disable" a method in a subclass. That would violate the substitutability principle and would break polymorphism. A subclass cannot remove visible members from the parent classes API.

提交回复
热议问题