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 Polymorphism understanding.... 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 "Polymorphism understanding...." Watch "Polymorphism understanding...." New topic
Author

Polymorphism understanding....

Alan Blass
Ranch Hand

Joined: Mar 21, 2010
Posts: 119
Hi! Give this code:



They give:

in Test Poly
hello superclass
test 1
hello superclass
test 2
hello superclass
test 1
hello superclass
test 2
hello superclass

My question is: What is the purpose of writing

TestPoly t1 = new Test1();

as oppose to Test1 t3 = new Test1();

since both give the same result?

Thanks.
Stephan van Hulst
Bartender

Joined: Sep 20, 2010
Posts: 3647
    
  17

http://www.coderanch.com/t/510989/java/java/reference-type
David Byron
Rancher

Joined: Jan 20, 2009
Posts: 172

Alan Blass wrote:
My question is: What is the purpose of writing

TestPoly t1 = new Test1();

as oppose to Test1 t3 = new Test1();

since both give the same result?


Stephan's link answers the question "Why declare as the parent type rather than the child type?" Using the reference type TestPoly (the parent) rather than Test1 (the child) allows for polymorphism; you can introduce new kinds of TestPoly (Test3, Test4, Whatever) without changing this code.

The flipside of the issue is the answer to the question "Why declare as the child type rather than the parent type?" You would want to declare the type as Test1 (the child) rather than as TestPoly (the parent) if you needed to invoke a method supported by that specific child but not by every TestPoly. For example, if Test1 included not only the inherited hello() and the overridden print() methods but also its own doTest1Stuff() method, then you would be unable to invoke the latter method without casting if the declared type were TestPoly.


SCJD 6, OCPJP7, Baroque Potion, G+
Alan Blass
Ranch Hand

Joined: Mar 21, 2010
Posts: 119
thanks.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Polymorphism understanding....