This week's book giveaway is in the Testing forum. We're giving away four copies of Data Structures the Fun Way: An Amusing Adventure with Coffee-Filled Examples and have Jeremy Kubica on-line! See this thread for details.
In the below example, when i print class of "this", it gives me SubClass (SCJPExam) name. But variable values are printed from Exam class. How does the system chooses the Exam class for getting the variable values?.
1) I understand that instance/static variables are not overridden and simply hidden in subclass.
2) If i override the method in SubClass, am able to print the values from SubClass.
Output: level is ---->easy2
level is ---->easy2
class is ---->class SCJPExam
Source: i copied this code form some site and forgot it now.
Method invocation is decided at runtime, based on the type of object being referenced,
whereas, since instance variables are not overrided through polymorphism, hence appropriate variable is chosen based on the type of reference variable.
Karthikeyan Kandasamy wrote:Thanks. Is it okay to assume that "variable values are sourced from class in which the method is defined"?.
Always.. (If you are using this reference to access that variable)
Karthikeyan Kandasamy wrote:
In the below example, variable "level" is declared in each class/interface.
In main function, am making the function call "printLevel" with Interface's reference but variable "level"'s value is sourced from a subclass (SCJPExam).
Output: level is ---->tough
level is ---->tough
class is ---->class SCJPExam_851
Try printing the variable level with the reference "t" in main..
Similarly you can create reference of class Exam and assign it to object of type SCJPExam_851
and print the variable level with that reference.. and See the output in both cases..
Instance variable never follow the rule of Overriding, but as you enter the method, you will have access to the variable in that class only through "this" reference..
Because compiler will see the smallest possible scope..
Why would you want to access variable of another class from the method defined in a different class, that too using a this reference??
The City calls upon her steadfast protectors. Now for a tiny ad: