Java主类实例访问

标签 java class compilation java-7 program-entry-point

我无法编译以下代码。无法理解这里的编译过程。为什么主类实例对其他类不可见(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);
 }

最佳答案

System.out.println(t.i); 语句应该在 block 或方法中。

例如,您可以或者将它放在一个 block 中(静态或非静态,没关系)。

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

    static { //static can be omitted
        System.out.println(t.i);
    }
}

或者地方在一个方法内

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

    public static void printSomething() { //static can be omitted
        System.out.println(t.i);
    }
}

更多信息(感谢@vidudaya):

关于Java主类实例访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20701652/

相关文章:

java - 用于识别解析错误的默认值(字符串 -> double /任何数字)

java - 分隔的整数列表

c++ - 从编译传递的宏无法在 Eclipse 中解析

javascript - 访问 Javascript ES6 类中声明的函数(ES2015?ES16?)

python - python 中 try 和 except 的使用

C++ 分发具有依赖关系的程序

c++ - 如何在包含树中找到哪个 header 包含另一个 header ?

java - 如何在java中向带有图形的框架添加按钮?

java - Findbugs 警告 : Integer shift by 32 -- what does it mean?

class - 如何在 Fortran 2003 中以多态方式解除分配?