Basically I would like to know why a static method cannot be shadowed by an instance method, (I know why, it will lead to ambiguity in certain circumstances), whereas a static variable can be shadowed by an instance variable (it applies only for subclasses).
Example:
public class Apartment{
static int area = 10;
public static int getArea(){
return area;
}
}
class BedroomFlat extends Apartment {
int area = 10;// no problem at all
public int getArea(){ // illegal line it cannot hide the super static method
return area;
}
}
So if I tried to declare int area
(instance variable) along with the static int area
in the super class it would give an error but it does not happen when declared in the subclass even though the static int area
is still visible from the subclass.
What's exactly the difference in terms of behavior between trying to shadowing a static method with an instance method and trying to shadowing a static variable with an instance variable.
Thanks in advance.
In your sub class (BedroomFlat), compiler will not allow you to declare a instance method with the same name as that of static method in the base class because method overriding is only applicable to instance methods. Extending a class only make instance methods available to the sub class for overriding(and not class methods i.e. static). Moreover, when you try to declare a method with same signature as that of a static method, compiler will throw an error saying you cannot override a static method, as overriding takes place for instance method.
But compiler will not stop you from declaring a instance variable with the same name as static one from super class, because variables are not the candidates for overriding.