C#介面和JAVA的區別?

來源:互聯網
上載者:User
文章目錄
  • 實現多個介面

介面是一種“主幹類”,包含方法簽名但是沒有方法的實現。在這個方面,介面與抽象類別一樣,只包含抽象方法。C# 介面非常類似於 Java 介面,工作原理基本一樣。

介面的所有成員都定義為公用成員,並且介面不能包含常量、欄位(私人資料成員)、建構函式、解構函式或任何類型的靜態成員。如果為介面的成員指定任何修飾符,編譯器將會產生錯誤。

為了實現介面,我們可以從介面衍生類別。這樣的衍生類別必須為所有介面的方法提供實現,除非衍生類別聲明為抽象的。

介面的聲明與 Java 完全一樣。在介面定義中,通過單獨使用 get 和 set 關鍵字,屬性僅指示它的類型,以及它是唯讀、唯寫的還是可讀寫的。下面的介面聲明了一個唯讀屬性:

 1public interface IMethodInterface
 2{
 3  // method signatures
 4  void MethodA();
 5  int MethodB(float parameter1, bool parameter2);
 6
 7  // properties
 8  int ReadOnlyProperty
 9  {
10    get;
11  }
12}
13
14

用一個冒號來代替 Java 的實現關鍵字,類就可以繼承此介面。實作類別必須提供所有方法的定義以及任何必需的屬性訪問器:

 1public class InterfaceImplementation : IMethodInterface
 2{
 3  // fields
 4  private int count = 0;
 5  private int ID;
 6
 7  // implement methods defined in interface
 8  public void MethodA()
 9  {
10    
11  }
12
13  public int MethodB(float parameter1, bool parameter2)
14  {
15    
16    return integerVariable;
17  }
18
19  public int ReadOnlyProperty
20  {
21    get
22    {
23      return count;
24    }
25  }
26
27  // add extra methods if required
28
29}
30
31

實現多個介面

通過使用下面的文法,一個類可以實現多個介面:

public class MyClass : interfacename1, interfacename2, interfacename3

如果一個類實現多個介面,則成員的名稱會存在二義性,通過使用屬性或方法名的完全限定符可以解決這個問題。換句話說,通過使用方法的完全限定名來指示它屬於哪個介面(例如屬於 IMethodInterface.MethodA),衍生類別可以解決這種衝突。

文章來自:http://www.microsoft.com/china/msdn/library/langtool/vcsharp/Usgettingstartedcsharpforjava.mspx?mfr=true

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.