Question:
java question about instance variables?
johnny
2011-12-02 15:49:26 UTC
What is wrong with the following code segment?
VendingMachine vend2 = new VendingMachine();
vend2.reset();
vend2.addCandy("Milky Way", 0.50);
System.out.println(vend2.totalItems);

1. The code tries to access a private instance variable.
2. The code tries to modify a static variable.
3. The code tries to modify a private instance variable.
4. There is nothing wrong with the code.

I've got this from the book. I've already picked #4 but which is wrong. I don't really see any errors. and I don't think its number 1 unless we suppose to assume they've already set to private?

can anyone help pick the right answer and explain? thanks!
Three answers:
McFate
2011-12-02 16:00:48 UTC
Nobody can give you a certain answer without seeing the definition of VendingMachine class.



The correct answer would be 1 IF VendingMachine's definition included "private int totalItems" or something like that (don't know if it's int [count of items], double [cost of items], Candy[] [array of items], etc.).



You can rule out 2 and 3 (the code doesn't try to modify any variables other than the method temporary "vend2", which is neither private nor static). So you are between 1 and 4. But if VendingMachine.totalItems is public then there are no problems, and if VendingMachine.totalItems is private then it's an error.
AnalProgrammer
2011-12-03 00:19:00 UTC
This line defines a variable vend2 of type VendingMachine

VendingMachine vend2 = new VendingMachine();



This line accesses the method reset() using the object vend2

vend2.reset();



This line access the method addCandy() using the object vend2

vend2.addCandy("Milky Way", 0.50);



This line is not accessing a method.

System.out.println(vend2.totalItems);



The answer is 1.



If the correct answer is 3 then you have not given all the information.

It is that word "Modify"

The only line that has a variable access in it is the print.

System.out.println(vend2.totalItems);

This is accessing the variable and NOT modifying it. All the other lines are using methods.

The answer is still 1!



Have fun.
deonejuan
2011-12-03 00:16:47 UTC
The usual practice is to use private instance vars with public getters() and setters()



That way, vend33 can have a different value for totalItems than vend2 does. I vote for No. 1 without seeing the textbook.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...