Q. Why can't two public classes be defined in one class scope in java?
A. Just the way the language is designed. Once you get used to it, you'll find it helps you organize your code.
Q. Why Class B can't become public?
A. It can, but it has to be in a file called B.java. And it has to be the only public class in that file.
Q. How can I use a class in other classes?
A. You might want to rephrase the question. But there are multiple approaches:
- Make the class public, instantiate it, and call methods on it.
- Add the class to the same file, don't make it public (you won't be able to), instantiate it, and call methods on it. You'll be able to use it from other classes in the same file or package. This is the "default" access modifier, and it means that you'll be able to instantiate this class from within other classes in the same package.
- Make it an inner (or nested) class, instantiate it, and call methods on it. It will only be accessible by name from within its parent class. This is supposed to increase encapsulation and make code more readable. http://docs.oracle.com/javase/tutorial/java/javaOO/nested.html
Q. Is it better to define it inside Cons?
A. I personally don't find myself doing that very often. I find it makes the code a bit messier, though the above links says otherwise.