使用Getters和Setter:初学者指南

时间:2015-02-01 03:28:49

标签: java setter getter

好的,所以我完全是初学者,只是在课堂上学习。谁能告诉我我做错了什么?当我运行这段代码时,它应该告诉我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());
   }
}

2 个答案:

答案 0 :(得分:2)

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

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

另外,你应该在某处调用myMonkey2.setWeight()。别忘了在某个地方拨打myMonkey.setColor(myFavoriteMonkeyColor)myMonkey2.setColor()

答案 1 :(得分:0)

简单。当您想要将值显式设置为对象中的变量时,可以使用getter和setter。这意味着您必须首先调用变量的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?