March 5, 2013
Completing a class definition
Question by user2086204
Suppose that you are given the following PetDriver class, which includes a main method:
public class PetDriver{
public static void main(String[] args){
int weight = 40;
Pet doggie = new Pet("Rover", weight);
System.out.println("my pet's name is " + doggie.getName());
System.out.println("my pet's weight is " + doggie.getWeight());
}
}
Executing main produces the following output:
my pet’s name is Rover
my pet’s weight is 40
My code is as follows but It is returning null.
public class pet {
public String name;
public int weight = 40;
public Pet (String y, int x){
y = name;
x = weight;
}
public String getName(){
return name;
}
public int getWeight(){
return weight;
}
}
Thanks!
Answer by Starx
Your constructor does not assign the value to the properties. Change them to the following.
public Pet (String y, int x){
name = y;
weight = x;
}