gpt4 book ai didi

java - “No Public Class” 在它的包中真的可以到达吗?

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:31:48 25 4
gpt4 key购买 nike

<分区>

在《Think in Java》中,作者说:

You just leave the "public" keyword off the class, in which case it has package access. (That class can be used only within that package.)

为了证明这一点,我创建了一个公共(public)类和一个非公共(public)类:

package com.ciaoshen.thinkinjava.chapter7;
import java.util.*;

//My public class
public class PublicClass {
//default constructor
public PublicClass(){
System.out.println("Hello, I am PublicClass.");
}
}

//Non public class
//It should be package reachable
class PackageReachableClass {
//default constructor
PackageReachableClass(){
System.out.println("Hi, I am PackageReachableClass.");
}
}

但是当我从同一个包中的另一个类调用它们时:

public class InPackageClass {

/**
* MAIN
* @param args void
*/
public static void main(String[] args){
//pubic class can be reached from anywhere
PublicClass newPublicClass=new PublicClass();
//non-public-class should be accessable in the same package
PackageReachableClass newPackageReachableClass =new PackageReachableClass();
}
}

系统警告我:不应该从它自己的源文件之外访问 no-public 类。

/Users/Wei/java/com/ciaoshen/thinkinjava/chapter7/InPackageClass.java:22: warning: auxiliary class PackageReachableClass in ./com/ciaoshen/thinkinjava/chapter7/PublicClass.java should not be accessed from outside its own source file
PackageReachableClass newPackageReachableClass =new PackageReachableClass();
^
/Users/Wei/java/com/ciaoshen/thinkinjava/chapter7/InPackageClass.java:22: warning: auxiliary class PackageReachableClass in ./com/ciaoshen/thinkinjava/chapter7/PublicClass.java should not be accessed from outside its own source file
PackageReachableClass newPackageReachableClass =new PackageReachableClass();
^
2 warnings
Hello, I am PublicClass.
Hi, I am PackageReachableClass.

所以我的问题来了:no-public 类是否仍然可以访问包?如果这是完全合法的,为什么 Java 禁止我们从同一包中的另一个文件调用它们?

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com