Reputation: 359
Say for class ClassOne
extends from ClassTwo
, classone
is the subclass and ClassTwo
is the superclass. if I went to another class and typed in: ClassTwo hello = new ClassOne();
Does this mean I can only use the methods that are in ClassOne
which have been inherited from ClassTwo
and not the methods that were originally in ClassOne
? (E.g a. method called void eat();
was in ClassTwo
and ClassOne
inherited it but the method void walk();
was only in ClassOne
and not in ClassTwo
so by using the hello
keyword, could I access the eat function and not the walk function?), I don't quite understand the concept of polymorphism. Can someone explain it very simply and by giving an example? Thanks you very much.
Upvotes: 0
Views: 91
Reputation: 1865
The question describes, mostly clearly, a SSCCE that you could also easily write up and test yourself.
The relationship of an object of a class to a method or field in that class is "has a".
The relationship of a subtype to a supertype is "is a".
In ClassTwo hello = new ClassOne();
, the declared type of hello
is ClassTwo
. The righthand expression evaluates with type ClassOne
but is then cast up to type ClassTwo
. And ClassTwos do not have a walk()
.
ClassTwos do have an eat()
, and so do ClassOnes. The magic happens when you also declare void eat()
in ClassOne (with the same method signature as its superclass). Overriding the method like this allows for different or extra behavior to happen when ClassOnes eat! ... Up to here I've dropped some terms that you can surely go on to look up for yourself. Now I'll just claim that the term 'eat' is being used polymorphically there. But that's only one small example. I can't encapsulate any concept so abstract but powerful.
Upvotes: 0
Reputation: 10676
Yes that is true, the system will see classOne
as a classTwo
in regards to available methods.
I like to think about these concept as buckets, in this case classOne
fits into a classTwo
bucket. If I put a classOne
in a classTwo
bucket i can only see the classTwo
bucket. However I could pick out the classOne
from the classTwo
bucket, that is I can cast it.
This also helps in the case of upcasting and downcasting, that is casting an object to a supertype or subtype. You either put the item in a basket(upcasting) or you take it out from the basket (downcasting).
This analogy might be crap but it helps me :)
To answer your question yes, you can't make a method-call to a method that is in classOne
if it is casted to a classTwo
.
This is handy anf many times preferable. Think of interfaces
, basically an interface tells your object to provide a set of methods. This way we can ensure that these methods are available to everyone calling that object, the contract the object has with it's surroundings.
Also a possible duplicate: Try to describe polymorphism as easy as you can
Upvotes: 1