R
raphfrk
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.
One option would be something like:
class SubClass extends MainClass {
void check(Object x) {
if(x instanceof String) {
check((String)x);
} else {
super.check(x);
}
}
void check(String x) {
System.out.println("Sub class: " + x);
}
}
This would override and only use the sub-class for processing Strings.
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.
One option would be something like:
class SubClass extends MainClass {
void check(Object x) {
if(x instanceof String) {
check((String)x);
} else {
super.check(x);
}
}
void check(String x) {
System.out.println("Sub class: " + x);
}
}
This would override and only use the sub-class for processing Strings.