james13
james13

Reputation: 45

Using Getters and Setters: a Beginners guide

Okay so I'm totally a beginner and just learning this in class. Can anyone tell me what I'm doing wrong? When I run this code it's supposed to tell me that myMonkey and myFavoriteMonkey are the same color... but I keep getting a null value for the output...

I've got this on another java page(?)

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");

   }
}

and this on a separate page

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());
   }
}

Upvotes: 1

Views: 185

Answers (2)

Vrashabh Irde
Vrashabh Irde

Reputation: 14367

Its simple. You use getters and setters when you want to explicitly set values to variables in your objects. Which means you have to call the setter on the variable first to set the value of the variable and then the getter to see the value that was set. In your example, you have to first set the color of your favourite monkey first by calling myMonkey.setColor(myFavoriteMonkeyColor). This will set the colour of myMonkey to myFavoriteMonkeyColor. Then calling the getter will get this value on both myMonkey and myFavoriteMonkey.

Also like the first answer mentions there is a bug in your setweight method.

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
}

Follow up read: Why use getters and setters?

Upvotes: 0

Elliott Frisch
Elliott Frisch

Reputation: 201399

Your setWeight(int) has a bug; you pass in w but use weight in the assignment. I'm pretty sure you wanted

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

Also, you should probably call myMonkey2.setWeight() somewhere. And don't forget to call myMonkey.setColor(myFavoriteMonkeyColor) and myMonkey2.setColor() somewhere as well.

Upvotes: 2

Related Questions