Java force fields inheritance

前端 未结 4 1558
离开以前
离开以前 2021-01-29 01:45

I know there have been lots of thread about Java inheritance (and i already read it), but they all stand for \"how it is\", and I need knowledge \"how to change it\". So, we hav

4条回答
  •  醉话见心
    2021-01-29 02:04

    Yes, there is a way do to this. You can apply pattern which called "Template method". Here is an example

    class Base {
    
         void someMethod() {
             int value = getValue();
    
             // calculate something
         }
    
         protected abstract int getValue();
    }
    
    class Derived extends Base {
    
        int getValue() {
             return 5;
        }
    }
    

    Where getValue() is your template method and you can insert any logic in your inherited classes implementations.

提交回复
热议问题