Two public classes in one file java

前端 未结 5 730
青春惊慌失措
青春惊慌失措 2020-12-09 17:58

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

相关标签:
5条回答
  • 2020-12-09 18:31

    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");
        }
    }
    
    0 讨论(0)
  • 2020-12-09 18:37

    yes, 2 top level public classes are not allowed in one file

    0 讨论(0)
  • 2020-12-09 18:39

    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.)

    0 讨论(0)
  • 2020-12-09 18:46

    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 .

    0 讨论(0)
  • 2020-12-09 18:48

    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 {
    
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题