| Author |
Doubt Regarding Polymorphism
|
vipul bondugula
Ranch Hand
Joined: Oct 14, 2010
Posts: 218
|
|
Hi ,
I am having a doubt regardig polymorphism. I have a base class Animal.child class Dog.
Ex:-Animal a = new Dog();
What this statement tells?In real time where this situation will occur...
Thanks in Advance,
Vipul.
|
Thanks
Vipul Kumar
|
 |
Ashwin Sridhar
Ranch Hand
Joined: Jul 09, 2011
Posts: 272
|
|
you are creating the dog object and giving it to a animal reference.
Such situation might occur when you create List Object.
List is a interface , so you create a Object for arrayList or any of the classes that implements List and referenc it to List .
List l = new ArrayList();
|
Ashwin Sridhar
SCJP | SCWCD | OCA
|
 |
vipul bondugula
Ranch Hand
Joined: Oct 14, 2010
Posts: 218
|
|
Thanks Ashwin,
This answer iam expecting. Actually my doubt starts here.we can directly write
ArrayList al = new ArrayList();
instead of
List l = new ArrayList();
What is the use in instantiating ArrayList and giving reference to List.?
Thanks in Advance,
Vipul.
|
 |
Seetharaman Venkatasamy
Ranch Hand
Joined: Jan 28, 2008
Posts: 5575
|
|
Typically, It is better to program with super class/interface reference, this avoid the a class specific implementation method call in your code. for example,
pretend you love Dog now,
after some time you decided to go for a cat since you dont like the Dog
if you could have been used like this
in(1), you may tempted to use Dog class specific method, later when you change Dog to Cat
you are required to change the line (1) also , so totally two lines are modified, so maintenance may be nightmare there!
this is a small example with two lines, think about thousands of line!
|
 |
vipul bondugula
Ranch Hand
Joined: Oct 14, 2010
Posts: 218
|
|
Thanks Seetharaman ,
Is this the only reason or any other logical reason. When i see that kind of statements iam confused a little bit.
and this is called as Run-time polymorophism,right?
can anyone tell me a real time example of this run-time polymorphism.
Thanks in Advance,
Vipul
|
 |
Seetharaman Venkatasamy
Ranch Hand
Joined: Jan 28, 2008
Posts: 5575
|
|
|
look at this hot thread!
|
 |
Seetharaman Venkatasamy
Ranch Hand
Joined: Jan 28, 2008
Posts: 5575
|
|
also, Please SearchFirst
|
 |
vipul bondugula
Ranch Hand
Joined: Oct 14, 2010
Posts: 218
|
|
Thanks Seetharaman,
I got my answer here.
"Polymorphism is defined as one interface to control access to a general class of actions."
This answer supports what you have said...Thank you for your suggestions..
Thank you.
|
 |
Seetharaman Venkatasamy
Ranch Hand
Joined: Jan 28, 2008
Posts: 5575
|
|
vipul bondugula wrote:Thanks Seetharaman
you are welcome
|
 |
Seetharaman Venkatasamy
Ranch Hand
Joined: Jan 28, 2008
Posts: 5575
|
|
vipul bondugula wrote:
"Polymorphism is defined as one interface to control access to a general class of actions."
Sorry for the late reply! I suggest you to read this
|
 |
 |
|
|
subject: Doubt Regarding Polymorphism
|
|
|