This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes cannot understand the point of downcasting in the following code Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "cannot understand the point of downcasting in the following code" Watch "cannot understand the point of downcasting in the following code" New topic
Author

cannot understand the point of downcasting in the following code

David Schwartz
Greenhorn

Joined: May 28, 2008
Posts: 10
how are you?
wanted to ask you why this code is using Downcasting (1st code fragment line 36-37)? i.e.
in the line below

should not the compiler dynamically 'find out' that it is dealing with a subclass of CurrentEmployee
and use the appropriate functions in that sub-class (BasePlusCommissionEmployee)?
thank you
=================

==============
BasePlusCommissionEmployee
==============

============
CommissionEmployee
=============

Christophe Verré
Sheriff

Joined: Nov 24, 2005
Posts: 14687
    
  16

You usually do it to call methods that a class has, but that its interface/super class has not. Methods getBaseSalary and setBaseSalary are called. Are these methods also in Employee ?


[My Blog]
All roads lead to JavaRanch
David Schwartz
Greenhorn

Joined: May 28, 2008
Posts: 10
Christophe Verré wrote:You usually do it to call methods that a class has, but that its interface/super class has not. Methods getBaseSalary and setBaseSalary are called. Are these methods also in Employee ?


yes, i believe they are in the Employee class
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38031
    
  22
Is that example from Deitel and Deitel? It looks familiar.

I agree that if you are not using any specific Commission methods, the cast is unnecessary.
David Newton
Author
Rancher

Joined: Sep 29, 2008
Posts: 12617

But it's inside an instanceof, so there must be a reason, no? And if there isn't, wow.
David Schwartz
Greenhorn

Joined: May 28, 2008
Posts: 10
yes it is from Deitel and Deitel book (5th edition)
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38031
    
  22
Get a newer edition than 5th. Get 6th or newer, which describe the new features in Java 5.

I had a quick look through my 6th edition Deitel and can't see that cast. Which example number is it in your edition?
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: cannot understand the point of downcasting in the following code
 
Similar Threads
java.util.UnknownFormatConversionException: Conversion = 'i' error
Needs help in editing
Help Please
how to test/run a simple inheritance hierarchy in Eclipse
Requiring boolean...