• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Liutauras Vilda
Sheriffs:
  • Rob Spoor
  • Junilu Lacar
  • paul wheaton
Saloon Keepers:
  • Stephan van Hulst
  • Tim Moores
  • Tim Holloway
  • Carey Brown
  • Scott Selikoff
Bartenders:
  • Piet Souris
  • Jj Roberts
  • fred rosenberger

Qn from dan exam

 
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
class A {
void m1(A a) {System.out.print("A");}
}
class B extends A {
void m1(B b) {System.out.print("B");}
}
class C extends B {
void m1(C c) {System.out.print("C");}
}
class D {
public static void main(String[] args) {
A a1 = new A();
B b1 = new B();
C c1 = new C();
A c2 = new B();
c2.m1(a1);
c2.m1(b1);
c2.m1(c1);
}
}
In the above code result is "AAA".
I thought it would be "ABC" .
Though c2 is an object of A it is given a reference of C.So it should act as C object at runtime.Can anyone explain.

thanks
ss
 
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Please note, that the methods are overloaded not overridden. When you call the method with the object c2 of type A, m(A a) is called. since the other functions are added in the subclasses and are not known in the A class.
Hope this helps?
Rikko
 
Ranch Hand
Posts: 1090
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Swetha
As Rikko said the methods are overloaded and notr overridden. When you call the methods on an instance of B. The B has inherited method m1() from its ancestors and they are executed and as C is subclass of B, m1() method of B can accept object of type C.
Swetha : Though c2 is an object of A it is given a reference of C.So it should act as C object at runtime.Can anyone explain.

c2 has been given a reference of B.
[ August 21, 2003: Message edited by: Anupam Sinha ]
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic