简体   繁体   中英

How static method inheritance and static variable inheritance differs?

I got a doubt while going through override functionality in java.

Consider the below code:

class Vehicle {
    static int speed = 50;

    public static void display() {
        System.out.println(speed);
    }
}

class Jeep extends Vehicle {
    int speed = 100;

    void display() {    //GETTING COMPILE TIME ERROR
        System.out.println(speed);//will print speed of Bike   
    }

    public static void main(String args[]) {
        Jeep b = new Jeep ();
        System.out.println(b.speed);

    }
}

I read that static methods cannot be overridden.

But in the above code, I declared a static variable 'speed' in parent class Vehicle. And I created an instance variable with same name 'speed' in child class. i didn't get any compile time error as I changed the value of the static variable 'speed' in child class.

I am facing compile time issue while trying to override the display method, while I am not getting any error while re-declaring the variable 'speed' even though both are static in parent class.

What may be the reason that, the subclass's speed variable hides the parent class's static speed variable , but not doing the same with the display method and showing compile time error ?

static functions are not part of a particular instance of an object, and polymorphism doesn't really make much sense unless it's applied to an object.

That's why you cannot override a static function.

In your code the subclass defines a field with the same name(speed) which is declared as a new field and the field in the superclass is hidden or in other words shadowed by subclass field with same name.

A shadowed field indicates that it is not inherited by the subclass instead the subclass has declared a field with same name in its scope.

Hiding of field does not affect its value in the superclass. To access the hidden field simply use super.fieldname (Vehicle.speed in your case since its static).

Fields cannot be overidden but only be hidden in java.

Shadowing of fields is considered as bad practice by many as it makes the code less readable and confusing.

As for why static fields cannot be overridden Bathsheba has provided an excellent answer on your question post or refer Why doesn't Java allow overriding of static methods?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM