Case :
I have an abstract class A. It contains two methods
abstract void search(Position p);
abstract void search(Animal a);
Class B and C extends A. I would like class B to implement search(Position p)
only and class C to implement search(Animal a)
only. However when I do so it gives an error, telling me to implement both of the method overloads.
How could I solve the problem? Any help is greatly appreciated
CodePudding user response:
Here are the rules for classes extending Abstract class
- First concrete/non-abstract class must implement all methods
- If abstract class extends Abstract class, it can but need not implement abstract methods.
Option 1: Interface Segregation
separate search(XXX) into two abstract classes
Option 2: Generics. Make search a Generic Type
public abstract class ClassA {
public abstract <T> void search(T t);
public static void main(String ...args){
ClassA classA = new ClassB();
classA.search(new Animal());
}
}
class Animal{
}
class ClassB extends ClassA {
@Override
public <Animal> void search(Animal t) {
System.out.println("called");
}
}
Option 3: Interface
public class ClassA {
public static void main(String... args) {
Searchable classA = new ClassB();
classA.search(new Animal());
}
}
interface Searchable {
public <T> void search(T t);
}
class Animal {
}
class ClassB implements Searchable {
@Override
public <Animal> void search(Animal t) {
System.out.println("called");
}
}
Option 4: Throw UnsupportedOperationException Exception(Not recomended)
class ClassB extends ClassA {
@Override
void search(Position p) {
throw new UnsupportedOperationException("Not Supported");
}
@Override
void search(Animal a) {
}
}