Reputation:
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?
Upvotes: 3
Views: 134
Reputation: 285403
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.
Upvotes: 1
Reputation: 13222
You are not actually assigning "tommy" to anyting in your constructor. The constructor is passed "tommy" to name but you never assign name to anything. You should have a attribute(variable) in class Puppy called name then assign 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" );
}
}
Now you are storing the name in the myPuppy object.
Upvotes: 0