Re: Partially overriding a method?
On 4/21/2011 11:31 AM, raphfrk@gmail.com wrote:
I was wondering if it is possible to override a method but only for
certain sub-classes of the method that the super-class supports.
For example:
class MainClass {
public static void main(String[] args) {
System.out.println("Started");
MainClass mc = new SubClass();
mc.check("Testing");
mc.check(7);
}
void check(Object x) {
System.out.println(x.toString());
}
}
class SubClass extends MainClass {
void check(String x) {
System.out.println("Sub class: " + x);
}
}
The call to mc.check() calls the main class's version of the method.
However, if I change the sub-class to:
class SubClass extends MainClass {
void check(Object x) {
System.out.println("Sub class: " + x);
}
}
then it uses the sub-class always.
Right. You've made the mistake (and you're not the first,
nor the last) of confusing overRIDING with overLOADING. In your
first example, the `check' method of SubClass does not override
the `check' method of MainClass; is is an overload (of the `check'
identifier). SubClass has two different methods named `check':
void check(String) ... // inherited
void check(Object) ... // defined locally
In your second example things are quite different: SubClass
has only one `check' method:
void check(Object) ... // overrides MainClass method
Note that this `check' has exactly the same signature as the
MainClass `check'; that's why it overrides. In your first example
the two `check' methods have different signatures and have nothing
to do with each other, as you may see by experimenting with
class HeroClass extends MainClass {
double check(short shrift, String along) ...
}
--
Eric Sosman
esosman@ieee-dot-org.invalid