Home > Back-end >  Optional overloaded methods when overriding
Optional overloaded methods when overriding

Time:07-23

Case :

I have an abstract class A. It contains two methods

  1. abstract void search(Position p);
  2. 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

  1. First concrete/non-abstract class must implement all methods
  2. 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) {

    }
}
  • Related