-1
class Myclass{
    int x;
    Myclass(int i){
      x = i;
   }
}

    class UseMyclass { //Why do I need another class?
     public static void main (String args[]){
     Myclass y = new Myclass(10);
     System.out.println(y.x);
   }
}

为什么我不能从 Myclass 中运行 main()?从书中它说我将运行 UseMyclass 所以我猜这将是我的文件名。为什么我不能只使用 Myclass 作为文件名并在其中运行 main() ?我是编程新手,所以我只是想弄清楚。

4

1 回答 1

3

You don't actually need another class. If you just put the main method into the class, it will work. For example, this code will work just fine:

class Myclass{
   int x;
   Myclass(int i){
      x = i;
   }
   public static void main (String args[]){
     Myclass y = new Myclass(10);
     System.out.println(y.x);
   }
}

However, separating the main class is a good idea when you are dealing with large programs with many classes. Then, you can sneak unit tests into main methods in other classes.

于 2013-09-06T00:14:27.003 回答