Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Super and sub classes

 
John Kirvan
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is their anyway possible for me to access sub class methods in my super class.
 
David Harkness
Ranch Hand
Posts: 1646
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Layne Lund
Ranch Hand
Posts: 3061
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

Layne
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic