我是 Java 新手,想知道如何使用 setter/getter 訪問其他類的屬性(如果它們是陣列)。
目前,我有一個日期類,它使用月/日/年的引數設定日期。我需要創建另一個類,該類使用 date 類來設定雇用日期以存盤為屬性,以及其他類。
我的代碼目前看起來像這樣:
public class DateClass {
private int month;
private int day;
private int year;
// MONTH
public int getMonth() {
return month;
}
public void setMonth(int month) {
this.month = month;
}
// DAY
public int getDay() {
return day;
}
public void setDay(int day) {
this.day = day;
}
// YEAR
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
// FULL DATE
public void setDate(int month, int day, int year) {
setMonth(month);
setDay(day);
setYear(year);
}
public int[] getDate() {
return new int[] { month, day, year };
}
}
這是第二類:
public class EmployeeClass {
private int[] dateOfHire;
public void setDateOfHire(int[] dateOfHire) {
dateOfHire.setDate(dateOfHire);
}
public String[] getDateOfHire() {
return dateOfHire.getDate(dateOfHire);
}
}
錯誤說:無法在陣列型別 int[] 上呼叫 setDate(int[])
我怎樣才能解決這個問題?謝謝!
uj5u.com熱心網友回復:
您需要進行一些更改。首先,您EmployeeClass應該有一個DateClass屬性而不是,int[]并且該setDateOfHire()方法必須呼叫具有 3 個引數的setDate()可用方法DateClass:
public class EmployeeClass {
private DateClass dateOfHire;
public void setDateOfHire(int[] dateOfHire) {
this.dateOfHire.setDate(dateOfHire[0], dateOfHire[1], dateOfHire[2]);
}
public int[] getDateOfHire() {
return dateOfHire.getDate();
}
}
這會奏效,但我建議你檢查一下你的類設計。讓int陣列定義日期是一種非常糟糕的做法。
uj5u.com熱心網友回復:
您正在宣告一個整數基元陣列 private int[] dateOfHire;
宣告一個DateClass簡單使用的陣列private DateClass[] dateOfHire
之前定義的基元或類[]決定了被初始化的陣列的型別
您可以將此 作為參考
uj5u.com熱心網友回復:
您需要創建一個 DateClass 物件才能使用其方法。考慮像這樣改變你的 EmployeeClass :
public class EmployeeClass {
private int[] dateOfHire; // not sure of the purpose of this array
private DateClass dateClassObject; // your variable name is up to you
public EmployeeClass () { // Constructor for this class
dateClassObject = new DateClass(); // created a new DateClass in the constructor
}
public void setDateOfHire(int[] dateOfHire) {
// this dateOfHire array is the array that is passed in when
// method is called. Do not confuse it the array declared as a property.
int day = dateOfHire[0] // assuming the day is in index 0 of the array
int month = dateOfHire[1] // assuming the month is in index 1 of the array
int year = dateOfHire[2] // assuming the year is in index 2 of the array
dateClassObject.setDate(month, day, year); // changed to dateClassObject. Also changed setDate to pass correct parameters
}
public int[] getDateOfHire() { // changed String[] to int[] because returned value of getDate() is a int array.
return dateClassObject.getDate(); // changed to dateClassObject. Removed the parameter.
}
}
uj5u.com熱心網友回復:
在setDateOfHire剛剛設定的值,而不是呼叫它的方法:
public void setDateOfHire(int[] dateOfHire) {
this.dateOfHire = dateOfHire;
}
將它與您在 DateClass 中實作 setter 的方式進行比較。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/328175.html
