Java中public class与class的区别

时间:2022-02-13 15:35:55

Java中public class与class的区别

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

//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

编译OK后,将生成三个class文件:A.class B.class  HelloDemo.class

与C++的区别:

  1. C++中public关键字不能修饰类,只能修饰成员变量,成员方法。
  2. C++没有包的概念,与之类似的是C++名字空间(比如:using namespace std)
  • 包中,只有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, java中的import与C++中的include就不是相似的东东。
}}

Main.java编译出错: 
 

Error:(8, 21) java: com.package1.A is not public in com.package1; cannot be accessed from outside package


请参考: java中的package/import概念