Overload and hide methods in Java

后端 未结 4 1808
离开以前
离开以前 2021-02-05 14:39

i have an abstract class BaseClass with a public insert() method:

public abstract class BaseClass {

 public void insert(Object object) {
  // Do so         


        
4条回答
  •  我在风中等你
    2021-02-05 15:16

    There is no way of hiding the method. You can do this:

    @Override
    public void insert(Object ob) {
      throw new UnsupportedOperationException("not supported");
    }
    

    but that's it.

    The base class creates a contract. All subclasses are bound by that contract. Think about it this way:

    BaseObject b = new SomeObjectWithoutInsert();
    b.insert(...);
    

    How is that code meant to know that it doesn't have an insert(Object) method? It can't.

    Your problem sounds like a design problem. Either the classes in question shouldn't be inheriting from the base class in question or that base class shouldn't have that method. Perhaps you can take insert() out of that class, move it to a subclass and have classes that need insert(Object) extend it and those that need insert(Object, Object) extend a different subclass of the base object.

提交回复
热议问题