File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Try This One!!!! Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Try This One!!!!" Watch "Try This One!!!!" New topic
Author

Try This One!!!!

Surya B
Ranch Hand

Joined: May 10, 2000
Posts: 98
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

Joined: Jul 10, 2000
Posts: 124
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

Joined: Nov 22, 2008
Posts: 18944
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();
}
}
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Try This One!!!!