Dear Ranchites,
Am confused with the principle of overriding when it comes to member variables. For example, in the following code:
class Exam {
public
String difficultyLevel = "easy";
public void diffLevel() {
System.out.println("parentmethod");
}
public void getDifficulty() {
diffLevel();
System.out.println("parent variable " + difficultyLevel);
}
}
class SCJPExam extends Exam {
public String difficultyLevel = "killing";
public void diffLevel() {
System.out.println("childmethod");
}
}
class ourMain {
public static void main(String args[]){
SCJPExam myExam = new SCJPExam();
Exam ex = new Exam();
myExam.getDifficulty();
System.out.println("value is " + myExam.difficultyLevel);
}
}
On executing the following code,
OUTPUT
childmethod
parentvariable easy
value is killing
Both member method (diffLevel) and member variable (difficultyLevel) are overridden.
In getDifficulty(), when a method is called the child method is invoked. In a similar fashion when a variable is printed,its taking the parent variable.
Whats the reason for such a behaviour? What happens when a variable is overridden ? How does the JVM maintain both the variables ?
Please help me.