Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't two public classes be defined in one file in java? [duplicate]

Tags:

java

class

Why Class B can't become public? How can I use class be in other classes? Is it better to define it 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();}
    }
like image 722
Bernard Avatar asked Nov 11 '12 06:11

Bernard


People also ask

Can we have two public classes in the same file in Java?

No, while defining multiple classes in a single Java file you need to make sure that only one class among them is public. If you have more than one public classes a single file a compile-time error will be generated.

Why we can not declare multiple public classes in single Java file?

So when we provide more than one public class in a program the compiler itself stops you by throwing an error. This is because later we can't confuse the JVM as to which class is to be its initial class, because only one public class with the public static void main(String args[]) is the initial class for JVM.

How many public classes can a Java file is allowed to have?

A single Java program can contain more than one class and there are no restrictions on the number of classes that can be present in one Java program. But each Java program should have one class declared as public to make it accessible for classes in a different package.

Can we define two classes in same file?

Yes, we can have multiple classes in same java file. But, there is one restriction over here, which is that you can have as many classes in one file but only one public class is allowed. If we try to declare 2 classes as public in the same file, the code will not compile.


1 Answers

As per java language specification, there can be only one public class in a file (.java) and file name should be same as public class name.

If you want class B accessible in other placs, you may create a separate B.java file and move your Class B code to that file.

This thread may give you some more information.

like image 162
kosa Avatar answered Sep 20 '22 10:09

kosa