我知道 Java 中所有访问修饰符之间的区别。private然而,有人问了我一个非常有趣的问题,我很难找到答案:接口和publicJava 中的接口有什么区别,特别是它如何用作类成员?任何帮助将不胜感激。
3 回答
的用处相信大家都知道public interface,所以在private/protected interface这里提一下。
Interfacesprivate可以是类定义的成员,可以在protected其中声明。
public class Test {
private interface Sortable {
}
protected interface Searchable {
}
}
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
*/
接口本身可以是包私有的,而不是其中的方法。您可以定义一个只能在定义它的包中使用(按名称)的接口,但它的方法像所有接口方法一样是公共的。如果一个类实现了该接口,它定义的方法必须是公共的。这里的关键是接口类型在包外不可见,而不是方法。
接口上的public、private和protected访问修饰符的含义与它们在类上的含义相同。我通常会在嵌套在类中的接口上看到这些修饰符。像这样的东西:
//: interfaces/RandomWords.java
// Implementing an interface to conform to a method.
package interfaces;
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();
}
}
接口声明可能包含以下访问修饰符:
public protected private abstract static strictfp
public:如果一个接口类型被声明为public,那么它可以被任何代码访问。
protected/private:访问修饰符 protected 和 private 仅适用于直接封闭类声明中的成员接口。Amember interface是一个接口,其声明直接包含在另一个类或接口声明中。
static:访问修饰符static仅与成员接口有关,与顶级接口无关。
摘要:每个接口都是隐式的abstract。此修饰符已过时,不应在新程序中使用。
strictfp:修饰符的作用strictfp是使接口声明中的所有浮点或双精度表达式都显式地为FP-strict。