• 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • Liutauras Vilda
  • Jeanne Boyarsky
  • paul wheaton
Sheriffs:
  • Ron McLeod
  • Devaka Cooray
  • Henry Wong
Saloon Keepers:
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Tim Moores
  • Mikalai Zaikin
Bartenders:
  • Frits Walraven

Polymorphism vs Casting

 
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
Marshal
Posts: 79956
396
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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?
 
Sheriff
Posts: 11343
Mac Safari Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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...
 
Joey Chen
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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
Posts: 11343
Mac Safari Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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.
 
author
Posts: 14112
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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.
 
Ilja Preuss
author
Posts: 14112
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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.
 
(instanceof Sidekick)
Posts: 8791
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
An object only has one type

I thought I got beat up for saying that once. Must have been in a different context.
 
Joey Chen
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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
Posts: 14112
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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.
 
Ranch Hand
Posts: 3389
Mac MySQL Database Tomcat Server
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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 ]
 
Raghavan Muthu
Ranch Hand
Posts: 3389
Mac MySQL Database Tomcat Server
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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
Posts: 15
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Yes, it is very clear now. Thanks to all that replied.
 
a wee bit from the empire
Gift giving made easy with the permaculture playing cards
https://coderanch.com/t/777758/Gift-giving-easy-permaculture-playing
reply
    Bookmark Topic Watch Topic
  • New Topic