• 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Bear Bibeault
  • Liutauras Vilda
Sheriffs:
  • Jeanne Boyarsky
  • Junilu Lacar
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Jj Roberts
  • Tim Holloway
  • Piet Souris
Bartenders:
  • Himai Minh
  • Carey Brown
  • salvin francis

Polymorphism understanding....

 
Ranch Hand
Posts: 172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Saloon Keeper
Posts: 12484
269
 
Rancher
Posts: 175
Clojure Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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.
 
Alan Blass
Ranch Hand
Posts: 172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks.
 
I'm gonna teach you a lesson! Start by looking at this tiny ad:
the value of filler advertising in 2020
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic