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 computer programming, variable shadowing occurs when a variable declared within a certain scope (decision block, method, or inner class) has the same name as a variable declared in an outer scope. At the level of identifiers (names, rather than variables), this is known as name masking.
When superclass and subclass contain the same method including parameters and if they are static. The method in the superclass will be hidden by the one that is in the subclass. This mechanism is known as method shadowing.
There are three types of variables in Java: Local, Instance, and Static.
Variable shadowing refers to the practice of naming two variables — for example, a global and a local variable or a local variable and a callback function parameter — with the same name and within scopes that overlap. The variable scoping rule states that inner scope can access variables defined in the outer scope.
Nobody could inherit static methods and fields because they are belong to class.
In your case you are not overriding getArea();
from parent, you are attempting to create method with the same signature - and it leads to compilation error.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With