example for variable hiding in java:
what is the output of below Java program?
class Base{
int i = 10;
public void fun(){
System.out.println("Base fun.."+i);
}
}
class Der extends Base{
static int i = 100;
public void fun(){
System.out.println("Der fun.."+i);
}
}
public class HidingDemo {
public static void main(String[] args) {
Base b = new Der();
b.fun();
}
}
Der fun..100
Base fun..10
Der fun..10
compile time error
There are two types of hiding in java: 1.variable hiding 2.method hiding
1.variable hiding : having same variable names in base class and derived class.
2.method hiding : having same static methods with same signature in base class and derived class.
When you have same variable names in both base class and derived class, it prefers always current class variable. In this case fun() of derived class is trying to print i, which will access i of Der class but not Base class. So it prints Der fun.. 100
Back To Top