Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Try This One!!!!

 
Surya B
Ranch Hand
Posts: 98
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What do u think is the output of the following program:
class c1
{
public int add(){return 2+3;}
}
class c2 extends c1
{
public int add(){return 2*3;}
}
class c3 extends c2
{
public int add(){return 100/5;}
void test()
{
System.out.println("add()="+add());
System.out.println("super.add()"+super.add());
System.out.print("((c2)this).add()=");
System.out.println(((c2)this).add());
System.out.print("((c1)this).add()=\t");
System.out.println(((c1)this).add());
}
}
public class testAgain
{
public static void main(String[] args)
{
c3 myC3 = new c3();
myC3.test();
}
}
Surya
 
Deepak M
Ranch Hand
Posts: 124
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Surya B:
Surya

What do YOU think is the output ?
CHeck out the JLS for a similiar problem.
The reasoning is : The type of the object is not changed due to casting. Thus add method of C3 class itself is invoked even if u cast !
Try making the methods static ! Then what do u THINK is the output ?

Deepak
P.S. BTW, is this question from the real exam ?
 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
We always have to remember that polymorphism will take place for overriding methods when we do some casting. If you have someother method in c1 and if you cast c2 to c1 at that time the object will call the method in c1.
class c1
{
public int add(){return 2+3;}
public int sub(){return 10-5;}
}
class c2 extends c1
{
public int add(){return 2*3;}
}
class c3 extends c2
{
public int add(){return 100/5;}
void test()
{
c1 c2obj = new c2();
c1 c3obj = new c3();
System.out.println("add()="+add());
System.out.println("super.add()"+super.add());
System.out.print("((c2)this).add()=");
System.out.println(((c2)this).add());
System.out.print("((c1)this).add()=\t");
System.out.println(((c1)this).add());
System.out.print("((c1)this).sub()=\t");
System.out.println(((c1)this).sub());
System.out.print("((c1)c2obj).add()=\t");
System.out.println(((c1)c2obj).add());
System.out.print("((c1)c3obj).add()=\t");
System.out.println(((c1)c3obj).add());

}
}
public class testAgain
{
public static void main(String[] args)
{
c3 myC3 = new c3();
myC3.test();
}
}
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic