Re: Inheritance
<ash.furrow@gmail.com> wrote in message
news:1162843287.191972.196200@f16g2000cwb.googlegroups.com...
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