• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

i dont get it??

 
Conor Muldowney
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
gotcha

thanks
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic