aspose file tools*
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 Spring in Action this week in the Spring 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: 14688
    
  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: 39422
    
  28
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: 39422
    
  28
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?
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: cannot understand the point of downcasting in the following code