下面是我講座中的示例代碼,它使用另一個類ListNode定義了一個名爲BasicLinkedList類的泛型類。爲什麼實現接口的泛型類不需要構造函數?
我明白接口不需要構造函數,但爲什麼BasicLinkedList作爲實現接口的類不需要構造函數呢?
下面是ListNode類代碼:
class ListNode<E> {
protected E element;
protected ListNode<E> next;
public ListNode(E item) {element = item; next = null;}
public ListNode(E item, ListNode <E> n) {element = item; next = n;}
public ListNode<E> getNext() {return this.next;}
public E getElement() {return this.element;}
}
代碼爲LinkedListInterface:
import java.util.*;
public interface LinkedListInterface<E> {
public boolean isEmpty();
public int size();
public E getFirst() throws NoSuchElementException;
public boolean contains(E item);
public void addFirst(E item);
public E removeFirst() throws NoSuchElementException;
public void print() throws NoSuchElementException;
}
最後的BasicLinkedList代碼:
import java.util.*;
class BasicLinkedList<E> implements LinkedListInterface<E> {
protected ListNode <E> head = null;
protected int num_nodes = 0;
public boolean isEmpty() {return (num_nodes == 0); }
...//other methods
沒有類_have_有一個構造函數wri在代碼中。如果沒有找到,編譯器會添加一個默認的。有什麼具體的事情讓你覺得他們是必需的嗎? – csmckelvey
'BasicLinkedList'有一個默認的構造函數 – Ramanlfc