[英]What is the difference between public, protected, package-private and private in Java?
[英]What is the difference between a public and private interface in Java
我知道Java中所有訪問修飾符之間的區別。 但是,有人問我一個非常有趣的問題,我很難找到答案:Java中的private
接口和public
接口之間有什么區別,特別是如何將其用作類成員 ? 任何幫助將不勝感激。
我相信大家都知道public interface
的用法,因此在這里我要提到private/protected interface
。
Interfaces
可以是類定義的成員,並且可以在其中聲明為private
或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訪問修飾符僅與直接封閉的類聲明中的成員接口有關。 member interface
是其聲明直接包含在另一個類或接口聲明中的接口。
static:訪問修飾符static
僅與成員接口有關,與頂級接口無關。
abstract:每個接口都是隱式abstract
。 該修飾符已過時,不應在新程序中使用。
strictfp: strictfp
修飾符的作用是使接口聲明中的所有float或double表達式都顯式為FP-strict 。
參考: Java語言和虛擬機規范
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.