File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes difficult Construction Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "difficult Construction " Watch "difficult Construction " New topic

difficult Construction

peter liu

Joined: Jan 15, 2001
Posts: 2
Determine the result of attempting to compile and run the following code:
class A {
public int Avar;
public A() {
public void doSomething() {
Avar = 1111;
public class B extends A {
public int Bvar = 2222;
public B() {
System.out.println("Avar=" + Avar);
public void doSomething() {
System.out.println("Bvar=" + Bvar);
public static void main(String[] args) {
new B();

The output is:

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
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.
peter liu

Joined: Jan 15, 2001
Posts: 2

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
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:

Hope that helps.

Jane Griscti
SCJP, Co-author Mike Meyers' Java 2 Certification Passport
Rajpal Kandhari
Ranch Hand

Joined: Aug 26, 2000
Posts: 126
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,<P>Raj.<BR>-------------------------<BR>Afforts should be Appriciated.<BR>-------------------------
I agree. Here's the link:
subject: difficult Construction
It's not a secret anymore!