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 ?