Force base method call

后端 未结 13 1869
独厮守ぢ
独厮守ぢ 2020-12-11 00:15

Is there a construct in Java or C# that forces inheriting classes to call the base implementation? You can call super() or base() but is it possible to have it throw a comp

13条回答
  •  佛祖请我去吃肉
    2020-12-11 00:33

    Not in Java. It might be possible in C#, but someone else will have to speak to that.

    If I understand correctly you want this:

    class A {
        public void foo() {
            // Do superclass stuff
        }
    }
    
    class B extends A {
        public void foo() {
            super.foo();
            // Do subclass stuff
        }
    }
    

    What you can do in Java to enforce usage of the superclass foo is something like:

    class A {
        public final void foo() {
            // Do stuff
            ...
            // Then delegate to subclass
            fooImpl();
        }
    
        protected abstract void fooImpl();
    }
    
    class B extends A {
        protected void fooImpl() {
            // Do subclass stuff
        }
    }
    

    It's ugly, but it achieves what you want. Otherwise you'll just have to be careful to make sure you call the superclass method.

    Maybe you could tinker with your design to fix the problem, rather than using a technical solution. It might not be possible but is probably worth thinking about.

    EDIT: Maybe I misunderstood the question. Are you talking about only constructors or methods in general? I assumed methods in general.

提交回复
热议问题