This week's book giveaway is in the Agile and other Processes forum. We're giving away four copies of The Mikado Method and have Ola Ellnestam and Daniel Brolund on-line! See this thread for details.
What will happen when you attempt to compile and run the following code? class Base { int i=99; public void amethod(){ System.out.println("Base.amethod()"); } Base(){ amethod(); } } public class RType extends Base{ int i=-1; public static void main(String argv[]){ Base b = new RType(); System.out.println(b.i); b.amethod(); } public void amethod(){ System.out.println("RType.amethod()"); } } 1) RType.amethod -1 RType.amethod 2) RType.amethod 99 RType.amethod 3) 99 RType.amethod 4) Compile time error why the answer is B.
William Brogden
Author and all-around good cowpoke
Rancher
Joined: Mar 22, 2000
Posts: 12269
1
posted
0
Because the addresses of variables are decided at compile time but methods are looked up dynamically. So - the line: System.out.println( b.i ) uses the address of i in the Base class. As far as the compiler is concerned, b is a Base reference. Bill
I think this question was answered before... and i guess the reason why the answer is B is becoz the methods are polymorphed but the instance variables are not..
_ _____ _ <br />Used to be a Java Programmer but now I work on Microsoft Technologies - Word, Excel and Outlook!
Barkat Mardhani
Ranch Hand
Joined: Aug 05, 2002
Posts: 787
posted
0
Thank you very much? But why the answer isn't c?
The subclass has no constructor. So an implicit contructor Rtype() will be invoked. That will first invoke super class constructor Base(). Base() class constructor is calling amethd(). Now because of polymophism amethod() of Rtype will be invoked because after all the object's actual type is Rtype(). That amethod will print the first line.. and I guess you know the rest of story...
Sabarish Sasidharan
Ranch Hand
Joined: Aug 29, 2002
Posts: 73
posted
0
Also note that, if the amethod() had private accessibility the amethod() invoked from the constructor of the Base class would be different... That is because private members cannot be overridden. This is shown in the code below which is the original code, modified a bit.
Sab<br /> <br />Perfection does not come from belief or faith. Talk does not count for anything. Parrots can do that. Perfection comes through selfless work.<br />Swami Vivekananda