我对抽象类中代码的实际实现以及它的意义有点困惑。
我为 Max 堆编写了代码,我想基于它创建一个抽象类,这样我就可以为不仅仅是“Max”堆的堆提供一个一般大纲。
我的MaxHeap的身体看起来像这样:
public class MaxHeap {
// A class for nodes, just has 3 fields, lchild, rchild, and value
private HeapNode top;
private List<HeapNode> heap;
public MaxHeap() {
this.top = null;
this.heap = new ArrayList<>();
}
//I won't go into the guts of these methods, but will explain
//Displays the heap like [1,2,3,4,5,...]
public void display() {...}
//Adds a new HeapNode to the end of heap, if empty sets to top
public void add(int value) {...}
//Deletes a HeapNode at index pos
public void delete(int pos) {...}
//Swaps 2 Nodes within the heap
protected void swap(int pos, int otherPos) {...}
//// These are the methods that actually differ depending on the
//// type of heap (maxheap, minheap, etc) so I would assume they
//// would be abstract methods if writing an abstract class?
|
|
V
//Called within add method, heapifys the heap after adding a new Node
protected void addHeapify(int pos) {...}
//Called within delete method, heapifys the heap after deleted Node
protected void deleteHeapify(int pos) {...}
//Called within deleteHeapify for "if (pos==0) {...}", delete max Node
protected deleteExtremum() {...}
}
我的问题反映了我究竟如何在更抽象的层面上实现这一点?我想把我的编码提升到一个新的水平,需要理解这一点。我会做一个这样的抽象类吗?
public abstract class Heap {
private HeapNode top;
private List<HeapNode> heap;
public Heap() {...}
// **************
// public methods
// **************
public void display() {...}
public void add(int value) {...}
public void delete(int pos) {...}
}
理解“抽象”原始类的正确方法将极大地帮助我。
在抽象类中添加字段和构造函数是否正确,即使添加、删除、交换和显示不会在不同的堆之间更改,这些方法也应该是抽象的吗?
我也想知道我是否应该使用接口,但它似乎是一个更严格的抽象类,我将无法定义添加,删除,交换和显示。
holdtom
相关分类