Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The wrong data being assigned to the wrong variable

Tags:

java

public class Puppy{

   public Puppy(String name){
      // This constructor has one parameter, name.
      System.out.println("Passed Name is :" + name ); 
   }
   public static void main(String []args){
      // Following statement would create an object myPuppy
      Puppy myPuppy = new Puppy( "tommy" );
   }
}

In the following code above, it assigned the name tommy to the variable myPuppy, so how come it's actually assigned to the variable name?


1 Answers

You ask:

so how come it's actually assigned to the variable name?

It's not, you're assigning nothing currently to any variable at present. In particular, you're not assigning anything within your constructor, although you may be fooled into thinking that you are due to that println in the constructor. Solve this by first giving Puppy a name field, and then by making an assignment to that name field from the parameter in the constructor

public class Puppy {
  // give Puppy a name field
  private String name; 

  public Puppy(String name) {
     // assign the field in the constructor
     this.name = name;
  }

  //....  getters and setters go here
  public String getName() {
     return name;
  }

  // you can do the setter method...

Also, you'll want to remove the System.out.println(...) from within the Puppy constructor as it doesn't belong there, unless it's there only to test the code, with plan to remove it later.

The println statement should be in the main method:

public static void main(String []args){
   // Following statement would create an object myPuppy
   Puppy myPuppy = new Puppy( "tommy" );
   System.out.println("myPuppy's name: " + myPuppy.getName());
}

You asked:

But it said passed name is NAME. But nothing is assigned to name, so how did name turned into tommy?

name is a String variable, and in your code its a specialized type of variable, a parameter. In the println statement it holds the value "tommy" because you passed that into the constructor when you called it, so the output will be "Name is tommy". Again this is because the name variable holds the value "tommy". The variable name will not be displayed and almost doesn't even exist in compiled code.

like image 156
Hovercraft Full Of Eels Avatar answered Mar 31 '26 10:03

Hovercraft Full Of Eels



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!