Hi can someone please help me,I am a novice programmer and I don't understand the following code.
How does one.bark()
automatically returns the statement under the first if
condition. How does the compiler know which if statement to display (because we are not passing the size while calling bark()
)? I know the object calls the function setSize
and passes the argument 70
to it. Does that mean that the value 70
becomes an attribute of the object one
?
Code:
class GoodDog {
private int size;
public void setSize(int s) {
size = s;
}
public int getSize()
{
return size;
}
void bark()
{
if (size > 60)
{
System.out.println("Wooof! Wooof!");
}
else if (size > 14)
{
System.out.println("Ruff! Ruff!");
}
else
{
System.out.println("Yip! Yip!");
}
}
}
class GoodDogTestDrive
{
public static void main (String[] args)
{
GoodDog one = new GoodDog();
one.setSize(70);
GoodDog two = new GoodDog();
two.setSize(8);
System.out.println("Dog one: " + one.getSize());
System.out.println("Dog two: " + two.getSize());
one.bark();
two.bark();
}
}
Yes. When you call one.setSize(70)
, the size
variable is saved as 70
in the one
object. When you call one.bark()
, size
is still 70
When creating an object of a class , the object receives a copy of all non-static members of the class.
GoodDog one = new GoodDog();
object one contains a special copy of size. Like wise object two will have its own copy of member variable size.
When you set the size using setSize() function , the one object's size variable is modified and will contain the same value until another value is assigned.
When you call the bark function using one function , it's own copy of size variable is taken and used inside the bark function.
Actually, 70
is not a new attribute, but the size
attribute takes the value 70
.
And since you have two distinct instances ( Dog one
and Dog two
) of GoodDog, each one has it's own attribute size
, which has it's own value (in this case 70
and 8
).
From there, when you call the bark
method, each instance ( one
/ two
) will check the if/else
statement according to it's own attribute's value (respectively 70
/ 8
).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.