How do I force a polymorphic call to the super method?

前端 未结 7 1053
猫巷女王i
猫巷女王i 2020-12-16 15:54

I have an init method that is used and overridden through out an extensive heirarchy. Each init call however extends on the work that the previous did. So naturally, I would

7条回答
  •  感动是毒
    2020-12-16 16:02

    Here's one way to raise an exception if a derived class fails to call up to the superclass:

    public class Base {
        private boolean called;
        public Base() { // doesn't have to be the c'tor; works elsewhere as well
            called = false;
            init();
            if (!called) {
                // throw an exception
            }
        }
        protected void init() {
            called = true;
            // other stuff
        }
    }
    

提交回复
热议问题