aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Upcasting doesn't work as intended; clarification needed Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Upcasting doesn Watch "Upcasting doesn New topic
Author

Upcasting doesn't work as intended; clarification needed

Sandra Bachan
Ranch Hand

Joined: Feb 18, 2010
Posts: 434
Hello,

I have taken code from Sierra/Bates, end of chapter 2, and am playing around with it:



Output is:

furry bray
stripes bray

How do I make output such as:

furry generic noise
stripes bray


Thanks!

Marriage Made in Heaven
http://www.youtube.com/user/RohitWaliaWedsSonia
Frits Walraven
Creator of Enthuware JWS+ V6
Bartender

Joined: Apr 07, 2010
Posts: 1695
    
  25

Hi Sandra,

You can't.

Two important rules apply here:
  • A reference variables type determines the methods that can be invoked on the object the variable is referencing
  • What method is called is decided at runtime based on the object type.

  • In your case the the method makeNoise() is allowed because the class of the reference variable Mammal has a method called makeNoise(). The actual method to be called is the method on the Zebra (because it overrides the one in Mammal)

    Regards,
    Frits
    Sandra Bachan
    Ranch Hand

    Joined: Feb 18, 2010
    Posts: 434
    Totally forgot about the overriding part; now I understand
    Sandra Bachan
    Ranch Hand

    Joined: Feb 18, 2010
    Posts: 434
    By the way, I noticed when I comment out makeNoise() in Zebra, it invokes makeNoise() in Mammal:




    Output:

    furry generic noise
    Frits Walraven
    Creator of Enthuware JWS+ V6
    Bartender

    Joined: Apr 07, 2010
    Posts: 1695
        
      25

    correct, now it just inherits the method from its super class.

    Regards,
    Frits
    Tahir Akram
    Ranch Hand

    Joined: Jul 03, 2007
    Posts: 37
    Sandra Bachan wrote:Hello,

    I have taken code from Sierra/Bates, end of chapter 2, and am playing around with it:



    Output is:

    furry bray
    stripes bray

    How do I make output such as:

    furry generic noise
    stripes bray


    Thanks!




    Output

    furry bray
    furry bray
    furry bray


    Tahir Akram
     
    I agree. Here's the link: http://aspose.com/file-tools
     
    subject: Upcasting doesn't work as intended; clarification needed