File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Super and sub classes Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Super and sub classes" Watch "Super and sub classes" New topic

Super and sub classes

John Kirvan

Joined: Feb 01, 2005
Posts: 12
Is their anyway possible for me to access sub class methods in my super class.
David Harkness
Ranch Hand

Joined: Aug 07, 2003
Posts: 1646
The normal way is to declare the method in your superclass and override it in the subclass. However, if you want to call a method only defined in your subclass, I suppose you can do so by casting:But my first questions would be "Why do you want to do this?" and "Are you sure this isn't a sign that the design is flawed?"
John Kirvan

Joined: Feb 01, 2005
Posts: 12
It is a case of difficult proffessor giving difficult assignment. Yeah he could have deffinently made it a lot easier on us, oh well at least im learning.
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
As David said, it would be more common for the superclass to implement the method to maybe do nothing at all, and for the subclass to implement it to do something meaningful.

This happens a lot in frameworks. A superclass might have all the code required to connect to a database, execute a query and return the result. Then subclasses might only provide the specific query.

Now, in some sense the superclass method is executing code in a subclass method. Any chance that's what your instructor wanted? If so, read up on "abstract methods" as a way to force the subclass to override getSql().

If your instructor was looking for David's solution, be worried. In a perfect world, a SuperClass should never have to know anything about any SubClasses.

Let us know how this works out in class!
[ February 04, 2005: Message edited by: Stan James ]

A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Layne Lund
Ranch Hand

Joined: Dec 06, 2001
Posts: 3061
Or you can make the method abstract. This is often used to force subclasses to override a method. Providing an empty method in the base (or super) class is only meaningful if it is okay for the subclass to NOT override the method and use the default "do nothing" implementation.


Java API Documentation
The Java Tutorial
I agree. Here's the link:
subject: Super and sub classes
It's not a secret anymore!