【问题标题】:why this class not compiling? [duplicate]为什么这个类不编译? [复制]
【发布时间】:2018-01-05 21:13:58
【问题描述】:

为什么会出现这个错误?请看以下代码。

class Test{
  Hello h=new Hello();
}

class Hello{
  int a=10;
  System.out.println(a);   // error identifier expected
}

【问题讨论】:

  • 你希望它在没有 main 方法的情况下如何运行?
  • 这有很多问题。没有 main() 函数。没有任何块的 System.out 函数。在 Test 中创建一个 main() 函数,并在将 System out 语句设为静态后将其放入静态中。

标签: java class variables scope


【解决方案1】:

使用相同的包创建类

public class Hello {

    public void print(){

        int a = 10;
        System.out.println("Number is :" +a);
    }
}

Crate 类在 Hello 方法的同一个包中设置 Main 方法

public class Main {
    public static void main(String args[]){

        Hello h1 =  new Hello();
        h1.print();
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-12
    • 1970-01-01
    相关资源
    最近更新 更多