How to force derived class to call super method? (Like Android does)

前端 未结 8 2281
余生分开走
余生分开走 2020-12-08 04:00

I was wondering, when creating new Activity classes and then overriding the onCreate() method, in eclipse I always get auto added: super.onCr

8条回答
  •  一生所求
    2020-12-08 04:09

    If you want to make absolutely sure that the superclass-method is called as well, you must trick a bit: Don't allow the superclass-method to be overwritten, but have it call an overridable protected method.

    class Super
    {
       public final void foo() {
          foo_stuff();
          impl_stuff();
       }
    
       protected void impl_stuff() {
          some_stuff_that_you_can_override();
       }
    }
    
    class Base extends Super
    {
      protected void impl_stuff() { 
         my_own_idea_of_impl();
      }
    }
    

    That way, the user must call Super.foo() or Base.foo() and it will always be the base-class version as it was declared as final. The implementation-specific stuff is in impl_stuff(), which can be overriden.

提交回复
热议问题