Forums Register Login

Using this to reference static variables

+Pie Number of slices to send: Send
I got this problem from one of the mock exams. Is it ok to access static members using the this reference?
---
Q. 17
What is the result of compiling and running the following code:

public class Test {
static int total = 10;
public static void main (String args []) {
new Test();
}
public Test () {
System.out.println("In test");
System.out.println(this);
int temp = this.total;
if (temp > 5) {
System.out.println(temp);
}
}
}

A. The class will not compile
B. The compiler reports and error at line 2
C. The compiler reports an error at line 9
D. The value 10 is one of the elements printed to the standard output
E. The class compiles but generates a runtime error
Answer is D.
+Pie Number of slices to send: Send
yes its fine.
static variables can be accesed using the name of the class or using one of the instances created from the class. this refers to an instance so it doesnt make a problem.
but static methods cant access non static variables.
+Pie Number of slices to send: Send
 

Originally posted by Roy Ben Ami:

but static methods cant access non static variables.


yes, so, u cant have something like System.out.println(this.total); inside your main method.
HTH
Raghav
[ January 23, 2002: Message edited by: Raghav Sam ]
+Pie Number of slices to send: Send
Thank You!
I knew that guy would be trouble! Thanks tiny ad!
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 727 times.
Similar Threads
Access to static variable
simple question
John Hunt M.E Q17
sample Q
q on testonline.com
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 07:00:12.