I code in Python a lot, and I frequently create classes. Now, I'm not sure if this is good Python form, but I just declare a class in the same file as my main().
class foo {
...
}
I'm wondering if it's good form in Java to do the same?
For example,
class foo {
public static int name;
public static int numPoints;
public static int[] points;
}
public class bar {
public static void main(String[] args) {
...
}
}
Does not throw errors in Eclipse, so it must be allowed. But is it okay to do? Would it be better to just declare this class in a separate file..?
Edit: I just want to emphasize that my new class literally is just a container to hold the same type of data multiple times, and literally will only have like 3 values. So it's total about 5 lines of code. The question is - does this merit a new file?
Depends on what you want the class to do. If it's only used by the class with main method, there's little loss in declaring it in the same file, although I'd prefer to declare it as a private static
inner class then, for clarity and less namespace clutter:
class Program {
public static void main(String[] args){ ... }
private static class Foo {
public int name;
public int numPoints;
public int[] points;
}
}
If >1 other class use your class, it is generally considered good form to have it in a file of its own. If it's declared as a public class
, it must be in a separate file with the same name as the class. (Unless its an inner class, of course. :)