问几个java问题What will be the output on compiling/running the following code?
public class MyThread implements Runnable
{
String myString = "Yes ";
public void run()
{
this.myString = "No ";
}
public static void main(String[] args)
{
MyThread t = new MyThread();
new Thread(t).start();
for (int i=0; i < 10; i++)
System.out.print(t.myString);
}
}
问题是,myString 不是public的,为什么main()最后一行不会报错呢? 我把main()移到另一个class中,也能run,都有点学糊涂了我 :P
第二个问题
public class Static
{
static
{
int x = 5;
}
static int x,y;
public static void main(String args[])
{
x--;
myMethod();
System.out.println(x + y + ++x);
}
public static void myMethod()
{
y = x++ + ++x;
}
}
这里有两个static, 一个是static{ int x = 5;} 另一个是static int x;
如何拿到在那个static{}中的x? 还想知道前者有什么用吗?
多谢!!
Answers:
1) Of course no error, since you are accessing t.myString inside t itself! Note that your main method is part of the MyThread class. Furthermore, Java's default access specification for member variables and methods is NOT private! The default specification allows access from any class in the same package. As your MyThread class is not in any package (effectively in the so-called "global" package), and I suppose so is your other test classes, myString is accessible.
2) The x in the first static scope cannot be accessed, because it is destroyed straightaway after it is declared! Note that static {...} structure is usually useful only in the global scope, i.e., outside any class. Basically, it provides static initialization routines to be executed before everything else (of course, there are still necessary initializations like class loading before this). Don't confuse the static code fragment with static member variable of a class.
2) The x in the first static scope cannot be accessed, because it is destroyed straightaway after it is declared! Note that static {...} structure is usually useful only in the global scope, i.e., outside any class. Basically, it provides static initialization routines to be executed before everything else (of course, there are still necessary initializations like class loading before this). Don't confuse the static code fragment with static member variable of a class.