Is there a way to override class variables in Java?

后端 未结 17 1313
没有蜡笔的小新
没有蜡笔的小新 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:17

    No. Class variables(Also applicable to instance variables) don't exhibit overriding feature in Java as class variables are invoked on the basis of the type of calling object. Added one more class(Human) in the hierarchy to make it more clear. So now we have

    Son extends Dad extends Human

    In the below code, we try to iterate over an array of Human, Dad and Son objects, but it prints Human Class’s values in all cases as the type of calling object was Human.

        class Human
    {
        static String me = "human";
    
        public void printMe()
        {
            System.out.println(me);
        }
    }
    class Dad extends Human
    {
        static String me = "dad";
    
    }
    
    class Son extends Dad
    {
        static String me = "son";
    }
    
    
    public class ClassVariables {
        public static void main(String[] abc)   {
            Human[] humans = new Human[3];
            humans[0] = new Human();
            humans[1] = new Dad();
            humans[2] = new Son();
            for(Human human: humans)   {
                System.out.println(human.me);        // prints human for all objects
            }
        }
    }
    

    Will print

    • human
    • human
    • human

    So no overriding of Class variables.

    If we want to access the class variable of actual object from a reference variable of its parent class, we need to explicitly tell this to compiler by casting parent reference (Human object) to its type.

        System.out.println(((Dad)humans[1]).me);        // prints dad
    
        System.out.println(((Son)humans[2]).me);        // prints son
    

    Will print

    • dad
    • son

    On how part of this question:- As already suggested override the printMe() method in Son class, then on calling

    Son().printMe();
    

    Dad's Class variable "me" will be hidden because the nearest declaration(from Son class printme() method) of the "me"(in Son class) will get the precedence.

提交回复
热议问题