Rob L
Rob L

Reputation: 3304

Is it correct and good Java style to use an abstract class in this example?

I am implementing an integer heap data structure in Java. However, there are two kinds of heaps I want to implement: a min heap and a max heap. I was thinking of doing the following:

abstract class Heap {

      private int data[]; //the heap implemented using an array
      private int size; //how large of a heap
      private int numberOfElements; //how many items currently in the heap

      public Heap( int size ) {

            this.size = size;
            this.data = new int[ size + 1 ];
            this.numberOfElements = 0;
      }

      public abstract void insert( int data );

      public abstract void delete( int data );

}

And then I was going to make two derived classes

class MinHeap extends Heap {

      //call super() and use the three data fields above
      //of course here I will add the abstract methods insert and delete
      //and code them according to the min heap specifications
}

 class MaxHeap extends Heap {

      //call super() and use the three data fields above
      //of course here I will add the abstract methods insert and delete
      //and code them according to the maxheap specifications

}

Would this be considered good, okay, neutral or bad style? I am relatively new to the basic object oriented design techniques. I was first thinking to make Heap an interface, but since no matter what kind of heap I create, I want there to always be a data array, a size and a numberOfElements variable, so I thought this may be best implemented as an abstract class. I want to create re-usable generic code. Also, I know in this case instead of using an int array, I could make a Comparable array instead.

Upvotes: 0

Views: 146

Answers (1)

ifloop
ifloop

Reputation: 8386

You will have to change the access modifier of your fields in your base class to protected (or like Jamey in the comment below suggested) add getters and setter. Apart from that you've done it the right way.

Upvotes: 4

Related Questions