Method and variable hiding:
Hi Praphakaran,
The term shadowing when your parent class has a member variable named x for example and in the sub class you are also creating a member with the same name, means shadowing the parent class member x. This is bad practice although. One thing must be clear that member variables are not overridden. Overriding and shadowning are two completely different things. While you talk about overriding you have
polymorphism in hand to avail with. Let us see the code:
class Base {
int x=10;
public void demo() {
System.out.println(�demo() of base class�);
}
}
Class subclass extends Base {
int x=20;
public void demo() {
System.out.println(�demo() of subclass�);
}
public static void main(String[] args) {
Base b1 = new subclass();
System.out.println(b1.x);//prints 20
B1.demo();//calls the subclass version(overridden version)
}
}
This may give the clear cut idea of shadowing and overridding.
So far as the term hiding is concerned we can also see that in the term when we redefine the method in the subclass that is static. I said redefine and it never means overriding because static methods can�t be overridden.
class Base1 {
static void display(){
System.out.println(�Base1 class display()�);
}
}
class Subclass1 extends Base1 {
static void display() {
System.out.println(�Subclass1 class display()�
}
public static void main(String[] args) {
Base1 b1 = new Base1();
b1.display();//base1 class�s method display() is called.
Base b2 = new subclass1();
b2.display();//base1 class version display() method is called
subclass1 s1 = new subclass1();
s1.display();//the subclass1 version of method display() called
}
}
In this case the reference variable matters instead of run type type of Object the reference variable holds. Although you will get sort of warning that static method should be called in static way means using class name but calling a static method using reference variable gives you no harm but leaves your code less readable.
You should call static methods in the following way:
Base1.display();//proper way to call static method
Subclass1.display(); //proper way to call static method
I hope this little explanation may help you!
With regards,
cmbhatt