• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

q on testonline.com

 
JayaSiji Gopal
Ranch Hand
Posts: 303
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 compiler reports an error at line 2
b The class will not compile
c The value 10 is one of the elements printed to the standard output
d The compiler reports an error at line 9
e The class compiles but generates a runtime error

i answered d, since static variables do not have a this reference.

but the correct answer is c.

can someone please explain?
 
Mike Gershman
Ranch Hand
Posts: 1272
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
line 9 sets temp to 10
line 11 prints temp as "10"

There are three ways to refer to static class variable "total" from within class "Test"
1. use the simple name "total"
2. use the class name "Test.total"
3. use a reference to the anonymous Test object "this.total"

If the statement in main() were "Test myTest = new Test();", you could also say "myTest.total"

Using an instance reference to access a class member is just an indirect way of using its class name to do it. Java doesn't care which object "this" or "myTest" refers to, it just determines the class of the reference and acts as if you said "Test.total". Even if you had said "Test myTest = null;", "myTest.total" would still work.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic