aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes q on testonline.com Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "q on testonline.com" Watch "q on testonline.com" New topic
Author

q on testonline.com

JayaSiji Gopal
Ranch Hand

Joined: Sep 27, 2004
Posts: 303
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?


SCJP 1.4, SCWCD 1.4<br /> <br />Thanks in advance!<br />Jayashree.
Mike Gershman
Ranch Hand

Joined: Mar 13, 2004
Posts: 1272
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.


Mike Gershman
SCJP 1.4, SCWCD in process
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: q on testonline.com