Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / First Aid / November 2006

Tip: Looking for answers? Try searching our database.

Inheritance

Thread view: 
ash.furrow@gmail.com - 06 Nov 2006 20:01 GMT
Is there anyway for a superclass to access/call a method that belongs
to a subclass? Thanks
Paul Hamaker - 06 Nov 2006 20:25 GMT
Yes, provided it's an overriding method.
--
http://javalessons.com  Paul Hamaker, SEMM
Teaching ICT since 1987
Oliver Wong - 06 Nov 2006 21:59 GMT
> Is there anyway for a superclass to access/call a method that belongs
> to a subclass? Thanks

   A typical design is to declare an abstract method in the superclass
which you expect the subclass to implement.

   - Oliver
Lew - 07 Nov 2006 00:07 GMT
>> Is there anyway for a superclass to access/call a method that belongs
>> to a subclass? Thanks

Actually, it's trickier in a way to prevent a superclass from calling a
subclass's method, if the subclass overrode a superclass method.

public class Foo
{
  public void someMethod()
  {
    overridableMethod();
  }

  public void overridableMethod()
  {
  }
}

and some other class:

public clsss Another
{
  public void doSomething()
  {
     Foo foo = new SubclassOfFoo();
     foo.someMethod();
  }
}

In doSomething() the someMethod() call will be to the overridden
SubclassOfFoo.someMethod(), if it exists.  If not, then in turn
Foo.someMethod() will call SubclassOfFoo.overridableMethod() if it exists.

This, of course, only applies to instance methods, not class methods.

This is part of why it is inadvisable to call overridable methods in a
constructor.  The constructor may try to call a child class's method, which in
turn might refer to unconstructed attributes of the child class instance.

Prevent overridability with the "final" keyword:
...
  public final void nonOverridable()
  {
  }

or by keeping the method private or package-private.

- Lew


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.