Search code examples
javaclassinheritancesuperclassstatic-typing

Accessing functions of an object's (dynamically chosen) subclass


I am trying to implement a simple binary heap class in which the user can choose whether they want a min or max heap.

I made the super class abstract:

abstract class Heap 
{
    size() { ... }

    peek() { ... }
}

The main method chooses to instantiate either the maxHeap or minHeap subclass.

public static void main(String[] args)
{
    Heap myHeap = new minHeap();
    if ( /* some condition */ )
        myHeap = new maxHeap();   
}

myHeap.insert(/* some value */);

The insert function is implemented differently in the min and max heap classes:

class minHeap extends Heap
{
    public void insert() { ... }
}

class maxHeap extends Heap
{
    public void insert() { ... }
}

Of course, calling insert() from main throws an error, since there is no such method in the Heap class. What would be the best way to programmatically choose between the very similar min and max heap implementations?


Solution

  • insert appears to have the same signature in both cases, so you can just pull it up to the superclass. It doesn't matter if they're implemented differently as long as the signatures are the same.

    Your Heap class then becomes

    abstract class Heap 
    {
        size() { ... }
    
        peek() { ... }
    
        abstract void insert();
    }