Determine the result of attempting to compile and run the following code: class A { public int Avar; public A() { System.out.println("AAA"); doSomething(); } public void doSomething() { Avar = 1111; System.out.println("A.doSomething()"); } } public class B extends A { public int Bvar = 2222; public B() { System.out.println("BBB"); doSomething(); System.out.println("Avar=" + Avar); } public void doSomething() { System.out.println("Bvar=" + Bvar); } public static void main(String[] args) { new B(); } }
The output is: AAA Bvar=0 BBB Bvar=2222 Avar=0
Why the doSomething() method is invoked from within A's constructor, it is actually B's version of doSomething() that is being invoked?
bill bozeman
Ranch Hand
Joined: Jun 30, 2000
Posts: 1070
posted
0
Has to do with late binding and method overriding. If you know that when you override methods, when you are at runtime you will get the method of the subclass, so the same rule applies here. You are creating a B() so when you call doSomething() you will get the method in class B if it exists. Bill
peter liu
Greenhorn
Joined: Jan 15, 2001
Posts: 2
posted
0
Thank you Bill,But if I want call doSomething() method in A's class in A's constuctor,How should I do?
Jane Griscti
Ranch Hand
Joined: Aug 30, 2000
Posts: 3141
posted
0
Hi Peter, You can add <code>super.doSomething()</code> to the class B ctor.
If you re-compile and run you get the following output:
Hello Peter, You can invoke doSomthing() method of the A class by instantiating class A. So replace "new B()" by "new A()". As in you original case .... Method invocation always determines the implementation of the method to be executed based on the actual type of the object. Keeping in mind that it is an object of B that is being initialized, it is not suprising that the method call DoSomething() in A() constructor results in the method from class B being executed. Regards Raj.
Regards,<P>Raj.<BR>-------------------------<BR>Afforts should be Appriciated.<BR>-------------------------