[英]My getMethod does not return the value in the setMethod: Java
public class OOP_10_Encapsulation {
private String firstName;
private String favFood;
private int age;
private float weight;
//create a set method for firstName
public void setFirstName(String firstName){
this.firstName = firstName;
}
//create a get method for firstName
public String getFirstName(String firstName){
this.firstName = firstName;
return firstName;
}
//create a set method for favFood
public void setFavFood(String favFood){
this.favFood = favFood;
}
//create get method for favFood
public String getFavFood(String favFood){
this.favFood = favFood;
return favFood;
}
//create a set method for age
public void setAge(int age){
this.age = age;
}
//create a get method for age
public int getAge(int age){
this.age = age;
return age;
}
//create a set method for weight
public void setWeight(float weight){
this.weight = weight;
}
//create a get method for weight
public float getWeight(float weight){
this.weight = weight;
return weight;
}
}
public class OOP_11_TestEncapsulation {
public static void main(String[] args) {
OOP_10_Encapsulation learner1 = new OOP_10_Encapsulation(); //create object of OOP_10_Encapsulation
learner1.setFirstName("Evander O A");
learner1.setAge(31);
learner1.setWeight(98.6F);
learner1.setFavFood("waakye");
System.out.println("Hi, my name is " + learner1.getFirstName());
}
}
我有這個挑戰,我無法理解。 當我在 main 方法中運行代碼時,get 方法不會返回 set 方法中設置的名稱"Evander OA"
。 實際上,我的 get 方法都沒有得到我需要它們得到的任何東西。
讓我們看一下您的一種 get 方法:
//create a get method for age
public int getAge(int age){
this.age = age;
return age;
}
get 方法(也稱為“getter”)的目的是從 object 中獲取某些內容,通常是您想要獲取的對象的一些屬性。
如果只是想獲取一個屬性,則不需要向 get 方法傳遞參數:
public int getAge(int age) // age parameter is useless
不僅在這里沒用,而且您也做錯了,在 get 方法中,您首先更改了屬性的值。 您實際上是在 getter 方法中執行集合:
this.age = age; // wrong
給定您的 getAge 方法代碼,讓我們看看當您調用以下代碼時它將如何執行:
System.out.println("Hi, my name is " + learner1.getAge())
function getAge 將在沒有參數的情況下被調用,盡管它需要一個參數。 所以很可能你將無法編譯這段代碼。 嘗試編譯類似的東西時出現以下錯誤:
因此,如果您使用 1、2、3 或任何數量的參數創建 function,那么您必須使用與 function 調用相同數量的 arguments 來調用它。 否則很可能該代碼將無法運行。
現在讓我們假設我用一些值作為參數來調用它,可能你也這樣做了。
System.out.println("Hi, my name is " + learner1.getAge(0))
這將會發生:
//create a get method for age
public int getAge(int age // which is 0){
this.age = age; // you set the age to 0, losing the old value
return age; // you return 0, because you no longer have the old value
}
你應該怎么做? 簡單的:
//create a get method for age
public int getAge(){
return age;
}
現在將此修復應用到您的所有 getter(get 方法),您就可以使用 go。 如果有不清楚的地方,請告訴我。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.