Java中public class与class的区别


Java中public class与class的区别

public关键字修饰的class,其类名称必须与文件名称完全一致,且一个文件【最多只能有一个】public class,但可以有多个非public关键字修饰的class,否则编译报错

//File name: HelloDemo.java  
package com.package1;  

public class Hello {  
}  

public class A{};  
private class B{};   // protected class B{};

编译出错:
Error:(4, 8) java: class Hello is public, should be declared in a file named Hello.java

Error:(7, 8) java: class A is public, should be declared in a file named A.java

Error:(8, 9) java: modifier private not allowed here //Error:(8, 11) java: modifier protected not allowed here


包中,只有public修饰的类,才能在包外部包可见,否则只是包内私有的类。

//File name: HelloDemo.java  
package com.package1;  

public class HelloDemo {  
    public static void main_test(String[] args) {  
        System.out.println("Enter ...");  
    }  
}  

class A{}  
class B{}
//File name: Main.java  
package com.company;  

public class Main {  
    public static void main(String[] args) {  
        System.out.println("Enter main ...");  
        com.package1.HelloDemo demo = new com.package1.HelloDemo();    
        com.package1.A a;    //没有import,也可通过全路径访问HelloDemo,