Is there a way to override class variables in Java?

后端 未结 17 1416
没有蜡笔的小新
没有蜡笔的小新 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条回答
  •  猫巷女王i
    2020-11-22 10:15

    Though it is true that class variables may only be hidden in subclasses, and not overridden, it is still possible to do what you want without overriding printMe () in subclasses, and reflection is your friend. In the code below I omit exception handling for clarity. Please note that declaring me as protected does not seem to have much sense in this context, as it is going to be hidden in subclasses...

    class Dad
      {
        static String me = "dad";
    
        public void printMe ()
          {
            java.lang.reflect.Field field = this.getClass ().getDeclaredField ("me");
            System.out.println (field.get (null));
          }
      }
    

提交回复
热议问题