Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Agile forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Member variable overriding problem

 
choks
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Dirk Schreckmann
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
choks,

Welcome to JavaRanch!

We ain't got many rules 'round these parts, but we do got one. Please change your display name to comply with The JavaRanch Naming Policy.

We request that display names follow the pattern FIRST_NAME + SPACE + LAST_NAME.

Thanks Pardner! Hope to see you 'round the Ranch!
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by choks:
What happens when a variable is overridden?


Variables aren't overridden, they are hidden. That is, they aren't polymorphic, which one you access is determined by the compile time type of the reference you use.

Try adding

Exam exam = myExam;
exam.getDifficulty();
System.out.println("value is " + exam.difficultyLevel);

to your code and see how the method call and the field access behave differently.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic