Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Good practice question from .VoodooExam Guess o/p

 
Vishy Karl
Ranch Hand
Posts: 116
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi friends,
this is a good one , guess the o/p. good luck,


Options :
a . 2
b . Compile error " No method matching get ( ) found in class Q026 . "
c . 5
d . NullPointerException thrown at run-time .
But the answer is none of these, can u get guess what it is
good luck
 
dennis zined
Ranch Hand
Posts: 330
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
B's get method
6
is this correct?
 
Pradeep bhatt
Ranch Hand
Posts: 8927
Firefox Browser Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
6
 
Lakshmi Saradha
Ranch Hand
Posts: 170
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Vishy,
Tha ans should be "B's get method" and 6
Here is how 6 is printed.
1)The line Q028 obj = new Q028();invokes the no-args constructor of the class B, which in turn invkes the no args constructor of A So i is incremented twice and the value is now '2'.
2) A ob =new A();This invokes the no-args constructor of A so, i is '3'.
3)Q028 invokes the getmehtod() of B. which returns (i+3) which is 6 now.
I hope I am right.
 
Vishy Karl
Ranch Hand
Posts: 116
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Guyz,
U all r right, actually missed one thing in the question, actually the output still remains the same.
Q028 obj = new Q028();
A ob = new A();
ob = (A)obj; //----------this is the change.
System.out.println(ob.get());
Now I want to confirm with u all ,the casting with (A)obj still call the get method of class B as Q028 extends B right ?? do explain
thanks,
 
dennis zined
Ranch Hand
Posts: 330
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Polymorphism is in play at ob = obj. ob which is of type A is assigned a subclass of its type Q028. The get() method is overridden in B and inherited in Q028. So which get() method is called will depend on the object's type at runtime which, according to your code, is Q028.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic