The difference between public and class in Java

  • 2020-04-01 02:09:55
  • OfStack

There are two ways to define a class when you write it:
Public class definition class:
Class definition class:
If a class is declared using public class, the class name must be exactly the same as the file name.
Example: define a class (file name: hello.java)


public class HelloDemo{    //Declare a class with a naming convention for the class name: capitalize the first letter of all words
    public static void main(String args[]){    //The main method
        System.out.println("HelloWorld!!!");    //System output, printed on the screen
    }
};

This class is declared using a public class, the class name is HelloDemo, but the file name is hello.java, so it will appear when compiled as follows Question:

Hello.java:1  class  HelloDemo  Is public and should be in the name HelloDemo.java Declaration in file 
public class HelloDemo{ //Declare a class whose name is capitalized

1, errors,
The above error indicates that because the public class declaration is used, the class name should be exactly the same as the file name, that is, "hellodemo.java" should be used for the class name.
If the class declaration USES class, the class name can differ from the file name, but the generated name must be executed.
Example: have the following code (file name: hello.java)

class HelloDemo{
    public static void main(String args[]){
        System.out.println("HelloWorld!!!");
    }
};

The file name is hello.java, the file name is not the same as the class name, but because the class declaration is used, the compilation does not produce any errors, but the generated *.class file name is exactly the same as the class declaration: hellodemo.class
Instead of executing Java Hello, you should execute Java Hello demo

In a *.java file, there can be only one public class declaration, but multiple class declarations are allowed


public class Hello{
    public static void main(String args[]){
        System.out.println("HelloWorld!!!");
    }
};
class A{};
class B{};

In the above file, three classes are defined, so the program compiles to form three *.class files.


Related articles: