This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Java in General and the fly likes Accessing subclass methods Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Accessing subclass methods" Watch "Accessing subclass methods" New topic
Author

Accessing subclass methods

shalaka wadekar
Ranch Hand

Joined: Mar 21, 2008
Posts: 37
Hi All,

I am in a sorrowful state. Please help me.

I am developing a sample code for my application. In my handler class, I have an object of another class. Now using this object I made a call on its method. This method returned an an abstract class. Now what I actually want is to call a method of a subclass of this abstract class. What do I do? Please suggest.

To quote an example, its something like this:


This is what I have so far. Now what I want is to call a method of the subclass of absclass from my handler class. How do I achieve this. Please help.



Regards,
Shalaka


shalaka
SCJP
SCWCD
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24183
    
  34

Hi,

If the method is declared in the abstract class, then just call the method on the abstract class reference; the subclass's implementation will be called. This is really the whole point of abstract classes.

If, on the other hand, the method is only declared in the subclass, then the only way to call the method directly is to cast the abstract class reference to the subclass, and call the method on the casted value; i.e.,

SubClass1 s1 = (SubClass1) b1;
s1.subclassMethod();

- or -

((SubClass1) b1).subclassMethod();

Of course, this will fail at runtime if b1 is not an instance of SubClass, but is in fact an instance of some other subclass of absclass; therefore it's generally a bad idea. If this is what's going on, then you should back up a little, describe the problem you're trying to solve, and we can help you design your classes better.


[Jess in Action][AskingGoodQuestions]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Accessing subclass methods
 
Similar Threads
Decorator pattern - please comment on my problem
Question regarding Proxy DP
Class.ForName Problem with Generics
interface and classes
Abstact Class