一个java源文件可以包含多个类,但是只能有一个是 public 的类 而且这个 public 类必须与文件名一样
例如,Test.java中是可以包含其他类的:
class A{ } class B{ } public class Test{ }
注意,同一源文件中的非public类不能用其他修饰符修饰:下面定义类A和类B时会报编译错误的:
private class A{ } protected class B{ } public class Test{ }
同一源文件中的非public类,其成员变量和成员方法的访问修饰符使用与普通public类相同,类的访问限定效果等同于同一包下未使用public修饰的类:
在包package1下分别定义Test.java和ClassB.java
ClassB.java:(注意是非public类)
package pacakge1; class ClassB { public ClassB(int id){ this.id1 =id; this.id2 =id; this.id3 =id; this.id4 =id; } private int id1; protected int id2; int id3; public int id4; }
Test.java:
package pacakge1; class ClassA{ public ClassA(int id){ this.id1 =id; this.id2 =id; this.id3 =id; this.id4 =id; } private int id1; protected int id2; int id3; public int id4; } public class Test { public static void main(String[] args){ ClassA a = new ClassA(1); System.out.println(a.id2); System.out.println(a.id3); System.out.println(a.id4); ClassB b = new ClassB(2); System.out.println(b.id2); System.out.println(b.id3); System.out.println(b.id4); } }
Test.java里面定义的类ClassA相当于与Test.java同一包名下定义的ClassB类.
假如在另一包名package2下增加Test2.java,是会报编译错误的:
package package2; import package1.*; public class Test2 { public static void main(String[] args){ //这句会报编译错误 ClassA a = new ClassA(1); System.out.println(a.id2); System.out.println(a.id3); System.out.println(a.id4); //这句也会报编译错误 ClassB b = new ClassB(2); System.out.println(b.id2); System.out.println(b.id3); System.out.println(b.id4); }