This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
Answers to these two questions are related to the concept of dynamic method binding and varible shadowing. As you can see, base class as well as a derived class, both have a method named test() and an integer variable i.These two classes do not have a non-default constructor. So, a default constructor will be specified for each one of them by the compiler. Now, when an object b is created using, class2Base b = new class2() This has reference type of class2Base and object type if class2. a default constructor of class2 will be called when we create an object using new operator. This default constructor will call the default constructor of the parent class as its first line. The object state is now initialized. The next line of code is: System.out.println(b.i). Variable shadowing is resolved on the basis of reference type, in this case, reference type is class2Base. So, integer i from base class ( which is initialized to 2 ) will be displayed. Next line is: b.test(). This has object type of class2, so overriden test method from class2 will be called and hence the output. Your second question can be explained in a similar manner. Concepts of variable shadowing and dynamic method binding are very important and it helps if you get it right once and for all. Hope this helps. Cheers!! [ December 01, 2005: Message edited by: soudamini.s shirkhedkar ]