一个 java class/file 可以是多个包裹的一部分吗?

Can one java class/file be part of more than one package?

我是 Java 的初学者,刚开始学习包和访问限制,所以我想知道是否有可能 Java class属于多个包。 我不是说子包。

不,不可能。

但是不同包中可以有同名的类,但同一个包中不能有两个同名的类。

您不能在同一个 class 中放置两次包声明。 包语句必须是源文件中的第一行。每个源文件中只能有一个包语句,它适用于文件中的所有类型。

但是您可以定义相同的 classes - 在两个包中使用相同的名称甚至相同的实现,但包名称必须不同。

阅读有关套餐的更多信息here

您可以在其他包中声明一个同名的class。 这不是设计应用程序的最佳实践。

从技术上讲,您可以在两个不同的包中使用具有相同内容的相同 class,但是当您在另一个 Java class 中使用这 2 个 class 时,您使用 class.

中的任何一个时都必须非常具体(绝对包名称)

举个例子...

这是 class Testing,它具有完全相同的成员,但在两个不同的包中定义,即 com.overflow.stackcom.stack.overflow

当它们在另一个 class Test 中使用时,您必须将它们都导入并为至少一个 Testing class 使用绝对包名称] 以便 Java 编译器了解哪个实例是哪个 class(或者,您可以对两个测试 class 实例使用绝对包名称)。

--

package com.overflow.stack;
public class Testing {
    public void whoAmI() {
        System.out.println(this.getClass().getCanonicalName());
    }
}

--

package com.stack.overflow;
public class Testing {
    public void whoAmI() {
        System.out.println(this.getClass().getCanonicalName());
    }
}

--

package com.Whosebug;

import com.overflow.stack.Testing;

public class Test {

    public static void main(String[] args) {
        // not using absolute package name
        Testing test1 = new Testing();
        test1.whoAmI();

        // must use absolute package name if want to use Testing class
        // from different package then above.
        com.stack.overflow.Testing test2 = new com.stack.overflow.Testing();
        test2.whoAmI();
    }
}

样本运行:

com.overflow.stack.Testing
com.stack.overflow.Testing

也就是说,如果您或您的团队或组织是此 class 的作者,那么您应该避免在不同的包中拥有 classes 的副本,因为这会导致冗余代码重复并且会让这些 classes 的消费者感到非常困惑。此外,这些副本很可能会不同步,并可能导致 RuntimeException 难以调试并可能导致应用程序崩溃。