簡體   English   中英

Java中的公共接口和私有接口有什么區別

[英]What is the difference between a public and private interface in Java

我知道Java中所有訪問修飾符之間的區別。 但是,有人問我一個非常有趣的問題,我很難找到答案:Java中的private接口和public接口之間有什么區別,特別是如何將其用作類成員 任何幫助將不勝感激。

我相信大家都知道public interface的用法,因此在這里我要提到private/protected interface

Interfaces可以是類定義的成員,並且可以在其中聲明為privateprotected

public class Test {  

    private interface Sortable {  
    }  

   protected interface Searchable {  
    }  

} 

示例1:-源

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 
*/  

接口本身可以是包私有的,而不是其中的方法。 您可以定義一個只能在其定義的包中使用的接口(按名稱),但其方法像所有接口方法一樣是公共的。 如果類實現該接口,則它定義的方法必須是公共的。 這里的關鍵是接口類型在包外部不可見,而不是方法。

接口上的publicprivateprotected訪問修飾符的含義與它們在類上的含義相同。 我通常看到嵌套在類中的接口上使用的這些修飾符。 這樣的東西:

//: 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM