简体   繁体   中英

Why do I need a class here?

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);
   }
}

Why can't I run main() out of Myclass? From the book it says I would be running the UseMyclass so I guess that would be my file name. Why couldn't I just use the Myclass though as the file name and run main() in there? I'm new to programming so I'm just trying to figure stuff out.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM