Wednesday, October 17, 2007

Don't Invoke Potentially Overridable Methods from a Constructor

You already know that you can't access any nonstatic things prior to your
superconstructor running, but keep in mind that even after an object's
superconstructor has completed, the object is still in an incomplete state
until after its constructor has finished. Polymorphism still works in a
constructor.

look at following example:-

public class B extends A

{

B()

{

}

public static void main(String[] arg)

{

new B().method();

}

public void method()

{

System.out.println("Class B method");

}

}

class A

{

A()

{

method();

}

public void method()

{

System.out.println("Class A method");

}

}

O/P will be

Class B method

Class B method

don't try this(called overridden method from constructor ) sort of stuff in
your code. If it's a final or private instance method, then you're safe
since you know it'll never be overridden.

No comments: