Two Laptop Bag*
The moose likes Beginning Java and the fly likes Polymorphism vs Casting Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Polymorphism vs Casting" Watch "Polymorphism vs Casting" New topic
Author

Polymorphism vs Casting

Joey Chen
Greenhorn

Joined: May 13, 2007
Posts: 15
In the Head First Java book, it stated that:
...with polymorphism, the reference and the object can be different. (e.g. Animal myDog = new Dog();


However, my Java instructor told me that the example given is not polymorphism, rather it is casting. My instructor told me polymorphism only pertains to methods.

I am confused now and don't know who to believe.

Can anyone help clarify this?

Thank you.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 37970
    
  22
Somebody said,
"any object has two different types.

The first one is the declared type . . .

The second type is the actual type. "
recently. it was actually Rob Prime, on this thread.

You will have an Animal class, possibly abstract, and other subclasses, eg Dog, Cat, Horse, Goldfish. All those classes have the same methods as Animal. By sayingyou are saying you wish to use those objects as Animals, and only use those methods which are already declared in Animal.

I don't think the line you quoted shows polymorphism, and it doesn't have a cast in, either, but you can get into far better arguments about what to call things than about what they mean.

Using casting would mean you want a method specific to a subclassNote you need two pairs of round brackets, one for the case operator, the other because the dot operator has higher precedence. Class casting is a hazardous activity, and there is more about it in the thread I quoted earlier.

Using polymorphism means you have the same method name, but a different content. So bonzo.move() means walk or run, and blubber.move() means swim. The compiler sees both objects as Animals, and sees that Animal has a move() method; the runtime sees one as a Goldfish and the other as a Dog, and finds the methods appropriate to each. This is called dynamic binding, as opposed to static binding. [You will sometimes hear this inaccurately called late binding as opposed to early binding.] try writing an Animal class and try out some polymorphism.

Is that any help to you?
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

When we say...

Animal myDog = new Dog();

...the reference to the Dog object is implicitly upcast to the supertype Animal. This is an example of assignment conversion (in this case, a widening reference conversion).

"In simple terms, polymorphism lets you treat derived class members just like their parent class's members." (Ref: Wikipedia: Polymorphism.) In this case, we are treating an instance of Dog as the parent type, Animal.

So with this upcasting, I think we do have polymorphism here. But we're not going to see polymorphic behavior until we call a method using this reference. For example, when we call the makeNoise() method on this Animal reference, we get Dog's implementation of the method...


"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
sscce.org
Joey Chen
Greenhorn

Joined: May 13, 2007
Posts: 15
Originally posted by marc weber:
When we say...

Animal myDog = new Dog();

...the reference to the Dog object is implicitly upcast to the supertype Animal. This is an example of assignment conversion (in this case, a widening reference conversion).

"In simple terms, polymorphism lets you treat derived class members just like their parent class's members." (Ref: Wikipedia: Polymorphism.) In this case, we are treating an instance of Dog as the parent type, Animal.

So with this upcasting, I think we do have polymorphism here. But we're not going to see polymorphic behavior until we call a method using this reference. For example, when we call the makeNoise() method on this Animal reference, we get Dog's implementation of the method...


Thanks for the replies. I think I got the jist of everything. However, I do have a follow-up question.

Marc, in your code example, you stated that "when we call the makeNoise() method on this Animal reference, we get Dog's implementation of the method..." which I tested and was true. However the Head First Java book seems to contradict this statement of yours though.

In the book, it mentions a superclass "Object" and a subclass "Snowboard." It states that "...even if the object is of type Snowboard, an Object reference to the Snowboard object can't see the Snowboard-specific methods.



However, you just provided an example just like this and called the Dog's makeNoise() method.

Am I misinterpreting the book?
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

Originally posted by Joey Chen:
...In the book, it mentions a superclass "Object" and a subclass "Snowboard." It states that "...even if the object is of type Snowboard, an Object reference to the Snowboard object can't see the Snowboard-specific methods...

In my example, the supertype, Animal, also had a makeNoise() method. So when the Dog reference was upcast to type Animal, we still had a makeNoise() method that could be "seen."

However, if the Dog class had "Dog-specific methods" (not in Animal), then we would not be able to call these from an upcast reference.

For example, suppose we modified the code to add a Dog-specific method doTricks(). This method is not in Animal, so when we try to call doTricks() using the Animal reference, it fails (see commented-out line below). In other words, the Animal reference to the Dog object "can't see" that method.

However, if we downcast our Animal reference back to its original type of Dog, then we can call the method.
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
Originally posted by Joey Chen:

In the book, it mentions a superclass "Object" and a subclass "Snowboard." It states that "...even if the object is of type Snowboard, an Object reference to the Snowboard object can't see the Snowboard-specific methods.


That is supposed to mean that you can't call methods that are *only* implemented in the Snowboard class - methods that don't override methods in Object.


The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
Originally posted by Campbell Ritchie:
Somebody said, recently. it was actually Rob Prime, on this thread.


Jesper correctly replied that that's wrong. An object only has one type, which is determined at runtime. An object reference also has a type, which is determined at compile time. Casting acts on the compile time type, polymorphism on the runtime type.
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
An object only has one type

I thought I got beat up for saying that once. Must have been in a different context.


A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Joey Chen
Greenhorn

Joined: May 13, 2007
Posts: 15
Originally posted by Ilja Preuss:


That is supposed to mean that you can't call methods that are *only* implemented in the Snowboard class - methods that don't override methods in Object.


I understand now. A follow-up question, please see the example below.

The code successfully outputted although the compiler gave me an error indicating to me that this isn't the right way to write this code. I'm assuming the last line in class DemoPoly should've been

My question is, do the same rules still apply even if I have a subclass implement an interface - I still shouldn't call a method that isn't implemented in a superclass?
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
Originally posted by Stan James:
An object only has one type

I thought I got beat up for saying that once. Must have been in a different context.


Ah, yes, you are right. That was in a different context.
Raghavan Muthu
Ranch Hand

Joined: Apr 20, 2006
Posts: 3344

Originally posted by Joey Chen:
....My question is, do the same rules still apply even if I have a subclass implement an interface - I still shouldn't call a method that isn't implemented in a superclass?


Yes, but not directly. The same as in your previous example which calls the makeNoise() method.

If a method which is implemented *only* in the specific subclass and when its being invoked through the generic superclass, it has to be invoked via proper casting!

Unless and otherwise, the compiler just checks for the presence of method only in the reference type and NOT the actual object type.



In the code sample above, you have an object of type "Dog" but it is assigned to the type "Animal". Here you "refer" the actual "Dog" instance through a "variable" of type "Animal". Since the makeNoise() method is present in the Animal class as well, the compiler does NOT give any error! Because, the compiler is very happy to just check ONLY the reference type!

But at the runtime, the method which is actually invoked is as that of Dog class's since the actual instance is of type Dog.

If at all you have a method which is ONLY present in the Dog Class but NOT in Animal class, the compiler is very upset by NOT finding the expected method in the reference type (Animal).

But you can convince the compiler through a cast saying that, "hey buddy! i know this method is present in the Dog class, so you can be sure that at the runtime the method present in the Dog class is what going to be called. Don't worry! There won't be any runtime exceptions because of the absence of this method". So, no one could blame you later!

So, you need to have an appropriate type casting when you invoke the methods which are present ONLY in the specific subclasses but via superclass references!

Does that help?
[ September 11, 2007: Message edited by: Raghavan Muthu ]

Everything has got its own deadline including one's EGO!
[CodeBarn] [Java Concepts-easily] [Corey's articles] [SCJP-SUN] [Servlet Examples] [Java Beginners FAQ] [Sun-Java Tutorials] [Java Coding Guidelines]
Raghavan Muthu
Ranch Hand

Joined: Apr 20, 2006
Posts: 3344

Originally posted by Joey Chen:


..In the book, it mentions a superclass "Object" and a subclass "Snowboard." It states that "...even if the object is of type Snowboard, an Object reference to the Snowboard object can't see the Snowboard-specific methods.



However, you just provided an example just like this and called the Dog's makeNoise() method.

Am I misinterpreting the book?


If you carefully read further few pages, you may get it as K & B have well explained this code snippet with a beautiful picture.

You try to interpret the code, especailly the second line. What do you get from it?

You are trying to assign the "Snowboard" object to the "most-generic" object of type "Object" (which is of type java.lang.Object). Can you expect the java.lang.Object class to have all the methods present in your SnowBoard class as well? (as that of Animal class being a super class contains the methods makeNoise(), eat() etc which all or many of its subclasses like Dog, Frog etc may also have).

Certainly Not. Am i right? That's why the compiler gives you an error which says, "hey dude! i am unable to find out the method you are trying to invoke via the Object class reference".

If that's gonna be the way, how many method should that Object class have? Won't it be too overloaded? As everyone may tend to make use of java.lang.Object for the generic upcasting! K & B book itself had covered this in a Question & Answer manner.

So, we have a separate hierarchy of classes (upto our requirement) and we do tell the compiler via an appropriate type casting! like




Is it clear now?
[ September 11, 2007: Message edited by: Raghavan Muthu ]
Joey Chen
Greenhorn

Joined: May 13, 2007
Posts: 15
Yes, it is very clear now. Thanks to all that replied.
 
jQuery in Action, 2nd edition
 
subject: Polymorphism vs Casting
 
Similar Threads
when to use casting
Polymorphism and Static methods
why use servlets?
MasterExam OO question
Certifications revisited (was: Javaranch's image discussion)