|
|
Re: Inheritance question
|
Posted: May 18, 2005 3:47 PM
|
|
1. When you redefine an instance variable (defining x in class B in your case) then it hides the definition of inherited variable with same name.
2. Same thing happends when you redefine a static method in descendant class.
The reference to hidden variable or method is resolved at compile time and not at run time. So, this.x in class B refers to hidden variable x = 2 in class B. However, inside class A, variable x refers to x in class A.
In first case, where you are calling method() from constructor, it is a case of overriding. When you redefine an instance method then it is a case of overriding and not hiding. However, redefining an instance variable is a case of instance hiding and not overriding.
In case of overriding, the reference to method() call is resolved at run time. Since you are saying new B(), method() in class B is called in both cases. It is so, because "this" in class A and class B construtor is referring to an instance of class B.
Change the method() definition and make it static in both class A and class B. This time you will get the result same as in case of variable x being hidden. This time, method() will be hidden and its reference will be resolved at compile time.
|
|