Overload and hide methods in Java

后端 未结 4 1806
离开以前
离开以前 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:03

    This sounds like a badly designed hierarchy -

    If no default exists and the user shouldn't call the method at all you can mark the method as @Deprecated and throw an UnsupportedOperationException as other posters have noted. However - this is really only a runtime check. @Deprecated only throws a compiler warning and most IDEs mark it in some way, but there's no compile time prevention of this. It also really sucks because it's possible to get the child class as a parent class reference and call the method on it with no warning that it's "bad" at all. In the example below, there won't be any indication until runtime that anything's wrong.

    Example:

    // Abstract base builder class
    public abstract class BaseClassBuilder {
        public final doBuild() {
            BaseClass base = getBase();
            for (Object obj : getObjects() {
                base.insert(obj);
            }
        }
        protected abstract BaseClass getBase();
        protected abstract Object[] getObjects();
    }
    
    // implementation using SampleClass
    public class SampleClassBuilder extends BaseClassBuilder {
    
        @Override
        protected BaseClass getBase() {
            return new SampleClass();
        }
    
        @Override
        protected Object[] getObjects() {
            Object[] obj = new Object[12];
            // ...
            return obj;
        }
    }
    

    However, if a sensible default exists, you could mark the inherited method as final and provide the default value inside of it. This handles both the bad hierarchy, and it prevents the "unforseen circumstances" of the above example.

    Example:

    public abstract class BaseClass { 
        public void insert(Object object) {
            // ...
        }
    }
    
    public class SampleClass extends BaseClass {
    
        public static final Long DEFAULT_PARAM = 0L;
    
        public final void insert(Object object) {
            this.insert(object, DEFAULT_PARAM);
        }
    
        public void insert(Object object, Long param) {
            // ...
        }
    }
    

提交回复
热议问题