Is there a way to override class variables in Java?

后端 未结 17 1299
没有蜡笔的小新
没有蜡笔的小新 2020-11-22 09:49
class Dad
{
    protected static String me = \"dad\";

    public void printMe()
    {
        System.out.println(me);
    }
}

class Son extends Dad
{
    protected         


        
17条回答
  •  孤独总比滥情好
    2020-11-22 10:37

    Why would you want to override variables when you could easily reassign them in the subClasses.

    I follow this pattern to work around the language design. Assume a case where you have a weighty service class in your framework which needs be used in different flavours in multiple derived applications.In that case , the best way to configure the super class logic is by reassigning its 'defining' variables.

    public interface ExtensibleService{
    void init();
    }
    
    public class WeightyLogicService implements ExtensibleService{
        private String directoryPath="c:\hello";
    
        public void doLogic(){
             //never forget to call init() before invocation or build safeguards
             init();
           //some logic goes here
       }
    
       public void init(){}    
    
    }
    
    public class WeightyLogicService_myAdaptation extends WeightyLogicService {
       @Override
       public void init(){
        directoryPath="c:\my_hello";
       }
    
    }
    

提交回复
热议问题