Java主类实例访问

1 java program-entry-point compilation class java-7

我无法编译以下代码.无法理解这里的编译过程.为什么主类实例对其他类(test1)不可见.为什么它没有编译.请帮忙.

public class test {
    public int i = 10;
    public static void main(String[] args) {
           System.out.println("test main");
    }
}
class test1 {
     test t = new test();
     System.out.println(t.i);
 }
Run Code Online (Sandbox Code Playgroud)

Kon*_*kov 7

System.out.println(t.i);声明应该是一个块或方法中.

例如,可以其放置一个块(静态或非静态,没关系)内.

public class test1 {
    test t = new test();

    static { //static can be omitted
        System.out.println(t.i);
    }
}
Run Code Online (Sandbox Code Playgroud)

或者放置在方法中

public class test1 {
    test t = new test();

    public static void printSomething() { //static can be omitted
        System.out.println(t.i);
    }
}
Run Code Online (Sandbox Code Playgroud)

更多信息(感谢@vidudaya):

  • 检查[this](http://stackoverflow.com/questions/15901973/why-does-system-out-println-have-to-be-inside-a-method) (2认同)