![](/img/trans.png)
[英]How to create a Class with multiple constructors that use the same parameter type
[英]Constructors with the same primitive type as parameter
我有一個任務要求我創建一個數據 Class 作為我所有其他類的“節點中心”,例如用於 LinkedList、堆棧和隊列的 class 以“提供”。 我在數據 class 中創建構造函數來處理 LinkedList、Stack 和 Queue 類。 在為隊列實現構造函數之前,我沒有遇到任何問題。 在我的數據 class 的堆棧部分中,我已經創建了一個公共數據構造函數,其中一個 int 作為構造函數中的參數。 當我嘗試使用 int 作為隊列參數創建另一個公共 Data 構造函數時,出現錯誤:Data(int) 已在 Data.xml 中定義。 這是我的堆棧代碼:
/*
STACK WITH AN ARRAY
*/
int size; //initialize size
int stackArray[]; //initialize array
int top; //initialize top
public Data(int size) //constructor
{
this.size = size;
this.stackArray = new int[size];
this.top = -1;
}
這是我的隊列代碼:
/*
QUEUE WITH AN ARRAY
*/
public int Queue[]; //establish queue array and variables
public int front;
public int rear;
public int queueSize;
public int len;
public Data(int nQueue)//constructor
{
size =nQueue;
len = 0;
Queue = new int[size];
front = -1;
rear = -1;
}
我該如何解決這個問題,以便我可以擁有 2 個具有相同參數類型的構造函數?
它們都是 int 類型的構造函數。 Java 不關心您命名 int 參數的名稱,因此它們看起來像同一個構造函數(至少對於 java 而言)。 由於不能有兩個具有相同 arguments 的構造函數,因此您有兩個選擇。
其中任何一個都將允許 jvm 區分您的兩個構造函數。
兩個方法或構造函數不能具有相同的名稱和相同的簽名。
在您的情況下,如果您調用new Data(10)
來創建Data
的實例,編譯器將不知道要調用哪個構造函數來創建實例。
您可以使用第二個boolean
參數來提及要創建的實例類型。
public Data(int size, boolean isQueue)//constructor
{
if(isQueue){
len = 0;
Queue = new int[size];
front = -1;
rear = -1;
}else{
this.size = size;
this.stackArray = new int[size];
this.top = -1;
}
}
JLS: §8.4.2 方法簽名
您不能創建兩個在列表中具有相同數量的參數及其類型的構造函數。 您可以做的是為 Queue 和 Stack 創建子類,並在各自的子類中為它們中的每一個定義構造函數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.