使用 Getters 和 Setters:初学者指南

Using Getters and Setters: a Beginners guide

好吧,我完全是个初学者,只是在 class 中学习这个。谁能告诉我我做错了什么?当我 运行 这段代码应该告诉我 myMonkey 和 myFavoriteMonkey 是相同的颜色......但我一直得到输出的空值......

我在另一个 java 页面上找到了这个 (?)

public class Monkey2 {
   private String color;
   private int weight;

   public void setColor(String color)  {
      this.color = color;
   }

   public String getColor(){
      return color;
   }

   public void setWeight(int w){
      this.weight = weight;
   }

   public int getWeight(){
      return weight;
   }

   public void swing()  {
      System.out.println("Swinging");

   }
}

这在单独的页面上

public class MonkeyApp  {
   public static void main(String[] args) {
      Monkey2 myMonkey = new Monkey2();
      Monkey2 myMonkey2 = new Monkey2();
      Monkey2 myFavoriteMonkey = myMonkey;

      String myFavoriteMonkeyColor = "black";
      int myMonkeyWeight = 75;

      myMonkey.setWeight(myMonkeyWeight);

      myFavoriteMonkey.swing();
      System.out.println("myMonkey: " + myMonkey +
         " color: " + myMonkey.getColor() +
          " weight: " + myMonkey.getWeight()); 
      System.out.println("myMonkey2: " + myMonkey2 + 
         " color: " + myMonkey2.getColor() +
         " weight: " + myMonkey2.getWeight());
      System.out.println("myFavoriteMonkey: " + myFavoriteMonkey + 
         " color: " + myFavoriteMonkey.getColor() +
         " weight: " + myFavoriteMonkey.getWeight());
   }
}

您的 setWeight(int) 有一个错误;您传入 w 但在作业中使用 weight 。我很确定你想要

public void setWeight(int w){
    // this.weight = weight;
    this.weight = w;
}

此外,您或许应该在某处调用 myMonkey2.setWeight()。并且不要忘记在某处调用 myMonkey.setColor(myFavoriteMonkeyColor)myMonkey2.setColor()

很简单。当您想要显式地为对象中的变量设置值时,您可以使用 getters 和 setters。这意味着您必须先调用变量的 setter 来设置变量的值,然后调用 getter 来查看设置的值。 在您的示例中,您必须首先通过调用 myMonkey.setColor(myFavoriteMonkeyColor) 来设置您最喜欢的猴子的颜色。这会将 myMonkey 的颜色设置为 myFavoriteMonkeyColor。然后调用 getter 将在 myMonkey 和 myFavoriteMonkey 上获得此值。

也像第一个答案一样,提到您的 setweight 方法存在错误。

public void setWeight(int w){ //w is the value you want to set 
    this.weight = w; //assign the class variable to the particular weight you set
}

跟进阅读:Why use getters and setters?