Search code examples
javainheritancepolymorphismoverriding

Java polymorphism top level method is called


I have an inherited object in a java project and I am trying to call the overriden method in the child object. For some reason the parent version of the method is being called. It was my understanding of polymorphism that the lowest version of a method is always called. Why is the parent version being called?

public class Generator
{
    public static void acceptPending()
    {
        System.out.println("top level is called");
    }
}

public class GeneratorNeo extends Generator
{
    public static void acceptPending()
    {
        System.out.println("neo level is called");
    }
}

public class Driver()
{
    public static void main(String[] args)
    {
        Generator gen = null;
        gen = new GeneratorNeo();
        gen.acceptPending(); // prints top level is called
    }
}

Solution

  • acceptPending is a static method, static methods are called based on the compile time type of the object ie Parent type. unlike instance methods.

    so removing static keywords from both classes would give you the expected behavior.