Invalid data assigned to the wrong variable

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 is assigned the name tommy to the variable myPuppy, so how is it actually assigned to the variable name?

+3


source to share


2 answers


You're asking:

so how is it actually assigned to the variable name?

This is not the case, you are currently not assigning anything to any variable. In particular, you are not assigning anything in your constructor, although you may be tricked into thinking that you are associated with this println in the constructor. Solve this by first giving Puppy the name of the field and then by assigning the name to that 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...

      

In addition, you'll want to remove System.out.println(...)

from the Puppy designer, because it does not belong there, unless it is only for testing code with a 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 name: " + myPuppy.getName());
}

      


You asked:

But he said the name was passed on to NAME. But no name has been assigned since the name became tommy?

name is a String variable , and in your code a specialized variable type is a parameter. In the println statement it contains the value "tommy" because you passed that to the constructor when you called it, so the output will be "Name is tommy". Again, this is because the name variable is "tommy". The variable name will not be displayed and almost does not exist in the compiled code.

+1


source


You are not actually assigning "tommy" to anyting in your constructor. The constructor is passed to "tommy", but you never name anything. You must have an attribute (variable) in the Puppy class called name and then assign the name to this.name. Example:

public class Puppy{
private string name = null;
public Puppy(String name){
// This constructor has one parameter, name.
this.name = 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" );
}
}

      



You now store the name in the myPuppy object.

0


source







All Articles