Thursday, March 13, 2008

Confusion about the Class Variable Q&E Page

Until very recently one of the questions on the Questions and Exercises: Classes page looked like this:

1. Consider the following class:

public class IdentifyMyParts { public static int x = 7; public int y = 3; } a. What are the class variables? b. What are the instance variables? c. What is the output from the following code: IdentifyMyParts a = new IdentifyMyParts(); IdentifyMyParts b = new IdentifyMyParts(); a.y = 5; b.y = 6; IdentifyMyParts.x = 1; b.x = 2; System.out.println("a.y = " + a.y); System.out.println("b.y = " + b.y); System.out.println("IdentifyMyParts.x = " + a.x); System.out.println("b.x = " + b.x);

The answer for part (c) confused some of you:

a.y = 5
b.y = 6
IdentifyMyParts.x = 2
b.x = 2

In fact we've received twenty emails in the last year from people who thought the tutorial was in error — that the correct value for a.x (and therefore the value of IdentifyMyParts.x) should be 1.

Actually the answer is correct, though it doesn't offer any explanation. The point of this question was to have you think about class variables. (In fact, the writer wrote IdentifyMyParts.x rather than a.x to give you a clue that this is a class variable.) What makes x a class variable is defining it as a public static int. This means that there is a single instance of x that is shared across every instance of IdentifyMyParts. When the first line of the following code snippet is executed:

IdentifyMyParts.x = 1;
b.x = 2;

Then x has a value of 1 for less than a nanosecond. When the second line of code is executed, x is set to a value of 2. Whether you call it IdentifyMyParts.x, a.x or b.x, it all refers to the same entity. For more information, see Understanding Instance and Class Members.

As a result of your feedback, we have improved the question and the answer.

Your continued feedback helps us improve the tutorial. Thanks!

No comments: