Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Using this to reference static variables

 
Ricardo Cortes
Ranch Hand
Posts: 140
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Roy Ben Ami
Ranch Hand
Posts: 732
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Raghav Sam
Ranch Hand
Posts: 412
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Ricardo Cortes
Ranch Hand
Posts: 140
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank You!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic