• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Using this to reference static variables

 
Ranch Hand
Posts: 140
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 732
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 412
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thank You!
 
reply
    Bookmark Topic Watch Topic
  • New Topic