Why can't two java classes be defined in one file in java?

Why can't class B be made public? How can I use a class in other classes? Is it better to define this inside Cons ?!

// public class B { why not? class B { int x; B (int n) { x=n; System.out.println("constructor 'B (int n)' called!"); } } public class Cons { public static void main(String[] args) {B b = new B();} } 
+6
source share
3 answers

According to the specification of the Java language, there can only be one public class in a file (.java), and the file name must match the name of the public class.

If you want class B to be available on other boards, you can create a separate B.java file and move the class B code to this file.

This thread may provide you with additional information.

+12
source

Q. Why can't two public classes be defined in a java class in Java?

A. Just how the language is designed. Once you get used to it, you will find that it helps you organize your code.

Q. Why can't class B be made public?

A. It can, but should be in the B.java file. And it should be the only public class in this file.

Q. How can I use a class in other classes?

A. You might want to rephrase the question. But there are several approaches:

  • Make the class public, create an instance of it, and call methods on it.
  • Add the class to the same file, do not make it public (you cannot), create it and call methods on it. You can use it from other classes in the same file or package. This is the default access modifier, and this means that you can instantiate this class from other classes in one package.
  • Make it an internal (or nested) class, create it and call methods on it. It will be available only by name from its parent class. This should increase encapsulation and make the code more readable. http://docs.oracle.com/javase/tutorial/java/javaOO/nested.html

Q. Is it better to define this inside Cons?

A. I personally do not do this very often. I find this makes the code a little messier, although the links above say otherwise.

+7
source

Put your classes in different files.

The class name must match the file name.

+1
source

All Articles