gpt4 book ai didi

java - Java中的公共(public)接口(interface)和私有(private)接口(interface)有什么区别

转载 作者:行者123 更新时间:2023-11-30 04:13:36 28 4
gpt4 key购买 nike

我知道Java中所有访问修饰符之间的区别。然而,有人问了我一个非常有趣的问题,我很难找到答案:Java 中的 private 接口(interface)和 public 接口(interface)有什么区别,特别是, 如何使用它作为类成员?任何帮助将不胜感激。

最佳答案

相信大家都知道public接口(interface)的使用,所以我在这里提一下private/protected接口(interface)的要点。

接口(interface)可以是类定义的成员,并且可以在那里声明私有(private) protected

public class Test {  

private interface Sortable {
}

protected interface Searchable {
}

}

<强> Example 1: -- Source

public class PrivateInterface {  
private interface InnerInterface {
void f();
}

private class InnerClass1 implements InnerInterface {
public void f() {
System.out.println("From InnerClass1");
}
}

private class InnerClass2 implements InnerInterface {
public void f() {
System.out.println("From InnerClass2");
}
}

public static void main(String[] args) {
PrivateInterface pi = new PrivateInterface();
pi.new InnerClass1().f();
pi.new InnerClass2().f();
}
}

/* Output:
From InnerClass1
From InnerClass2
*/

It's the interface itself that can be package-private, not the methods in it. You can define an interface that can only be used (by name) within the package it's defined in, but its methods are public like all interface methods. If a class implements that interface, the methods it defines must be public. The key thing here is that it's the interface type that isn't visible outside the package, not the methods.

关于java - Java中的公共(public)接口(interface)和私有(private)接口(interface)有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18982838/

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