I don't have a problem with code I'm working on, I just want to ask a question about something regarding creating classes. In some cases, like this project, we create classes in separate .java files (apple.java, snake.java, etc). But some of the other tasks we have done previously have us create multiple classes in the same file (for example, several tasks related to working with Dog and Cat objects which were both in the same file). I was just wondering if someone could clarify when the classes go in separate files and when they go in the same file? Would this project work if GameObject, Snake, and Apple were all defined within SnakeGame instead of separate files?
Just want to ask clarification on where classes are declared
You must be signed in to leave a comment
24 July 2021, 08:06
(If you're not talking about inner classes... ) You can have several classes in one file but you only can have one public class in a file. The filename must match the public class (if you have one). Each class can have an own main method and each main method can of course be executed. That may be useful to bundle the 'main' class with support classes that may be just useful for that very main class. When you're learning this also may be useful to bundle code for better readibility. Another possibility to have several classes inside one class file are inner classes. Those are very useful constructs and you'll learn more about them later in this course (still at first you'll ask why they may be useful ;) )