QUOTE:
_______________________________________________________________________
MY QUESTION: Why does the code output A? I thought that if a non-static method was overridden, then the most specific method ought to be called because the actual object is of type C. Isn't this the basis of polymorphism?
_______________________________________________________________________
The code above outputs A because when you create
A c1 = new C();
what happens is that the object "c1" of class A gets created. It gets instantiated by default constructor for class C i.e. C().
The default constructor of subclass C calls default constructor of superclass B().Now subclass B() calls superclass A's default constructorA()in turn.
You can check this by using the following code.
_______________________________________________________
class A
{
A(){int k=1; System.out.println("k="+k);}
void m1(A a)
{ System.out.print("A"); }
}
class B extends A
{
B(){int j=1; System.out.println("j="+j);}
void m1(B b)
{ System.out.print("B");}
}
class C extends B
{
C(){int i=1; System.out.println("i="+i);}
void m1(C c)
{ System.out.print("C");}
}
class D
{
public static void main(
String[] args)
{
A c1 = new C();
C c2 = new C();
c2.m1(c2);
}
}
____________________________________________________
This gives an output like
k=1 j=1 i=1//c1 instantiated
k=1 j=1 i=1//c2 instantiated
C //prints C
prints C as you wanted. Incase you use the call by c1.m1(c2) "A" will be printed and so for other objects too.This will happen irrespective of the class you call to instantiate the object i mean..
A c1 = new B();
B c3 = new C();
C c2 = new C(); //can't be A() as this A is the superclass.
c3.m1(c2);//c3 is object of B so B will be printed.This wasn't
//the case earlier.
Overloading states that
Overload: you use different arguments and can change the method but with the same name. Constructors can be overloaded not overridden.
Overridden: They have to be inherited. Allows you to change the method implementation but should have not only the same name but also same type of arguments and return type.
The methods are overloaded not overridden as Brian said.
Hope it helps...... :roll:
[ July 17, 2004: Message edited by: natarajan raman ]