File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes i dont get it?? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "i dont get it??" Watch "i dont get it??" New topic
Author

i dont get it??

Conor Muldowney
Greenhorn

Joined: Dec 19, 2005
Posts: 15
Hey all i was just wondering why this compiles ok? should the "a" variable in run() not cause an error becasue its not in a static method?

public class Pmason implements Runnable{
static String a;
public static void main(String argv[]){
Pmason pm = new Pmason();
}
Pmason(){
a="alpha";
Thread t = new Thread(this);
t.start();
Thread t1 = new Thread(this);
a="zebra";
t1.start();
}
public void run(){
for(int i=0; i < 5; i ++){
System.out.println(a);
}

}
}
Keith Lynn
Ranch Hand

Joined: Feb 07, 2005
Posts: 2367
Originally posted by Conor Muldowney:
Hey all i was just wondering why this compiles ok? should the "a" variable in run() not cause an error becasue its not in a static method?

public class Pmason implements Runnable{
static String a;
public static void main(String argv[]){
Pmason pm = new Pmason();
}
Pmason(){
a="alpha";
Thread t = new Thread(this);
t.start();
Thread t1 = new Thread(this);
a="zebra";
t1.start();
}
public void run(){
for(int i=0; i < 5; i ++){
System.out.println(a);
}

}
}


No, because instance methods can access static members of a class. A static method can't access the instance variables in a class definition.
Conor Muldowney
Greenhorn

Joined: Dec 19, 2005
Posts: 15
gotcha

thanks
 
 
subject: i dont get it??
 
Similar Threads
Thread doubt
Thread Code doubt
doubt in thread
wait() and notifyAll()
synchronized uncertainty