Search code examples
javainheritancesubclassabstracta-star

Java subclass methods are not overriding despite explicit use of @Override


I am trying to make an abstract algorithm class for informed search with different heuristics. My idea was to have different subclasses overwrite the default heuristic() method, but the dynamic binding seems not to be working when I call the subclasses.

In astar.java:

public interface Astar {
    abstract String heuristic();
}

In search.java

public class Search implements Astar {
    public String heuristic() { return "default heuristic"; }
}

In EuclidianSearch.java:

public class EuclidianSearch extends Search {
    @Override
    public String heuristic() { return "Euclidian"; }
}

In ChebyshevSearch.java:

public class ChebyshevSearch extends Search {
    @Override
    public String heuristic() { return "Chebyshev"; }
}

In main.java:

EuclidianSearch e_search = null; ChebyshevDistance ch_search = null;
Search[] SearchObjects = {e_search, ch_search};

for(Search so : SearchObjects) {
    System.out.println(so.heuristic());
}

When run, it displays:

default heuristic
default heuristic

I define the array in terms of Search so I can be flexible: eventually, I want to have five or more different heuristics. Why doesn't the heuristic() method of the subclass override that of the superclass?


Solution

  • You will get NullPointerException for calling so.heuristic() because you don't instance class, use these codes :

    EuclidianSearch e_search = new EuclidianSearch();
    ChebyshevDistance ch_search = new ChebyshevDistance();
    

    but it is not sufficient to solve you problem, you should implement AStart interface by diffrent classes. don't forget that a class which implement a interface should implement all interface method. otherwise, you should define an abstract class to define only some methods and override remain methods in other classes with extend you previous class.

    public class Search implements Astar {
    
        @Override
        public String heuristic() { return "default heuristic"; }
    }