Ok, this might be kiddies question in java. We can\'t define two public classes in one file. But, in one of the examples from the book SCJP study guide, this example was men
Yes you can have two classes in the same file. You can have them by removing the public access modifier from both the class name, like shown below,
abstract class A{
public abstract void show(String data);
}
class B extends A{
public void show(String data){
System.out.println("The string data is "+data);
}
public static void main(String [] args){
B b = new B();
b.show("Some sample string data");
}
}
yes, 2 top level public classes are not allowed in one file
Imagine you could place two public classes in one file, then think about the work of the compiler: it has to build a .class file from your .java file that represents exactly one class (otherwise the .class ending wouldn't make any sense).
The way the JAVA Compiler works it will simply create a .class file with the name of your file and will search for the class with the name of the file in your given file – so it depends on your file name which class will be correctly compiled and which will not.
Long story short: no, you can't put two public classes in one file because the compiler wouldn't be able to handle that correctly.
(Edit: it of course is possible to define new classes INSIDE the one public class that has the same name as your file.)
you can make 2 public classes in one file , inside a class that contains them .
it's also recommended to add "static" for them , if you do not need any reference to the container class .
Well, if one is being so picky: you can have multiple classes defined with a public modifier in the same file, that is, using the static nested(inner) class. like this:
File -> Test.java
public class Test {
public static class SomeNestedClass {
}
}