choks

Greenhorn
+ Follow
since Nov 06, 2003
Merit badge: grant badges
For More
Cows and Likes
Cows
Total received
0
In last 30 days
0
Total given
0
Likes
Total received
0
Received in last 30 days
0
Total given
0
Given in last 30 days
0
Forums and Threads
Scavenger Hunt
expand Ranch Hand Scavenger Hunt
expand Greenhorn Scavenger Hunt

Recent posts by choks

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.
19 years ago