What is the purpose of having more than one class in a java file.I am new to java.
Edited: That can again be achieved by creating a inner class inside public class right?
What is the purpose of having more than one class in a java file.I am new to java.
Edited: That can again be achieved by creating a inner class inside public class right?
Varies... One such example would be an anonymous classes (you'll encounter those alot when using event listeners and such).
Yes, it can. However, there can only be one public class per .java file, as public classes must have the same name as the source file.
The purpose of including multiple classes in one source file is to bundle related support functionality (internal data structures, support classes, etc) together with the main public class. Note that it is always ok not to do this -- the only effect is on the readability (or not) of your code.
A public class must be implemented in a file with the same name as the class. A single file can contain one public and optionally some private classes. This is useful if the classes are only used internally by the public class. Additionally the public class can also contain inner classes.
Although it is fine to have one or more private classes in a single source file, I would say that is more readable to use inner and anonymous classes instead. For example one can use an anonymous class to define a Comparator class inside a public class:
public static Comparator MyComparator = new Comparator() {
public int compare(Object obj, Object anotherObj) {
}
};
The Comparator class will normally require a separate file in order to be public. This way it is bundled with the class that uses it.
In general, there should be one class per file. If you organise things that way, then when you search for a class, you know you only need to search for the file with that name.
The exception is when a class is best implemented using one or more small helper classes. Usually, the code is easiest to follow when those classes are present in the same file. For instance, you might need a small 'tuple' wrapper class to pass some data between method calls. Another example are 'task' classes implementing Runnable or Callable. They may be so small that they are best combined with the parent class creating and calling them.
Besides anonymous inner classes, another use is private inner classes that implement a public interface (see this article). The outer class can access all private fields and methods of the inner class.
This lets you create two tightly-coupled classes, such as a model and its view, without exposing the implementations of either. Another example is a collection and its iterators.
Yes, as much as you want!
BUT only one "public" class in every file!
Bye,
Alberto