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


i trying implement simple binary heap class in user can choose whether want min or max heap.

i made super class abstract:

abstract class heap  {     size() { ... }      peek() { ... } } 

the main method chooses instantiate either maxheap or minheap subclass.

public static void main(string[] args) {     heap myheap = new minheap();     if ( /* condition */ )         myheap = new maxheap();    }  myheap.insert(/* value */); 

the insert function implemented differently in min , max heap classes:

class minheap extends heap {     public void insert() { ... } }  class maxheap extends heap {     public void insert() { ... } } 

of course, calling insert() main throws error, since there no such method in heap class. best way programmatically choose between similar min , max heap implementations?

insert appears have same signature in both cases, can pull superclass. doesn't matter if they're implemented differently long signatures same.

your heap class becomes

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

Popular posts from this blog

c# - ODP.NET Oracle.ManagedDataAccess causes ORA-12537 network session end of file -

matlab - Compression and Decompression of ECG Signal using HUFFMAN ALGORITHM -

utf 8 - split utf-8 string into bytes in python -