2014-02-19 51 views
1

我讀了很多關於java中的接口。我知道你可以實現多態和其他偉大的東西(函數指針..等)。我有理論上的知識,但有些甚至沒有實踐。我一直在使用很多已經制作好的接口,如「Runnable」或大量的「聽衆」。但我仍然無法100%理解他們。如果有人會回答下面的問題,也許我會得到更好的理解:Inteface。爲什麼在這種情況下很有用

所以最近我正在學習LibGdx,我遇到過稱爲「Disposable」的Interface。它有一個名爲「dispose()」的方法,並且此方法的文檔說明了這一點。

發佈此對象的所有資源。

所以我認爲這個接口聲明如下:

public interface Disposable { 

public void dispose(); 

} 

而且我有一個實現此接口的類。

public class Main implements Disposable { 

@Override 
    public void dispose() { 
     // TODO Auto-generated method stub 

    } 

} 

問題:這個方法在被調用的時候怎麼做,如果它是空的?它不能處置任何東西..

我可以有我自己的方法在這個類誰會處置對象。爲什麼我們需要這個接口?

這只是一個例子。我遇到過很多類似的界面。

我真的無法理解像這樣的接口。

任何幫助appriciated。

回答

1

通常,庫提供接口,因此您可以擴展接口而不是更改內部代碼。這將保持使用該庫的代碼的兼容性。

提供空實現取決於開發人員,但在接口文檔中他們提供了應該實現接口的具體類的實際實現。

1

爲您的使用情況下,可能的原因:

  1. 你可能會在以後更改類的實現和實際需要處置的東西。客戶端代碼不應該改變。
  2. 這個類可能是大型數組的一部分,或者是各種事物的集合,其中很多都需要處理。允許更統一的代碼。
  3. 所有客戶代碼應該需要做的就是致電dispose。這在垃圾收集器模式中很有用,所以你可以做garbageCollector.collect(disposable)。如果接口是某些GarbageCollector包的一部分,這將是有意義的。
  4. 有時語言功能使用實施的方法。請嘗試使用資源 - 它只需要close,並且需要AutoCloseable,see here進行比較。
1

原因是,如果你有另一個對象的方法接受一種類型的Disposable,它期望(確實需要)由接口指定的方法存在。可能是因爲它會在某處調用該方法。

通過這種方式,您可以擁有多個實現Disposable的類(每個都以各自的方式),然後您可以通過Disposable接口傳遞該類的實例,該接口將公開接口指定的任何方法。而獲得Disposable實例的類可以依賴那個方法。

0

問題是,你可能有許多不同類型的對象,他們都想被處置。現在,你可以自己編寫一系列if-else語句,試圖確定給定的Object是否是某種其他類型對象的實例,以便確定如何處理它(以及觸發它的方法)或您可以像在這裏一樣定義一個通用的interface,希望在某個時間處理的所有物體都可以使用。

這意味着您可以基於這個單一的共同的interface來引用這些不同的對象中的每一個,使它們全都出現爲實例Disposable,這是多態性的基石。

這意味着無非就是一個Disposable對象列表,您可以快速方便地調用各自的dispose方法。來電者並不在意這是如何實現的,只是在被調用時纔會執行所需的合同...

0
There is a term in Java "Coding to Interfaces". 

Check the link: 
http://stackoverflow.com/questions/1970806/coding-to-interfaces 

Coding to an interface rather than to implementation. This makes your software/application easier to extend. In other words, your code will work with all the interface’s subclasses, even ones that have not been created yet. 
Anytime if you are writing code that interacts with subclasses, you have two choices either; your code directly interacts with subclasses or interacts with interface. Like this situation, you should always favor/prefer to coding to an interface, not the implementation. 
To use the interface one can simply call the methods on an instance of the concrete class. 

One would call the methods on a reference of the type interface, which happens to use the concrete class as implementation: 

List<String> l = new ArrayList<String>(); 
l.add("foo"); 
l.add("bar"); 
If you decided to switch to another List implementation, the client code works without change: 

List<String> l = new LinkedList<String>(); 
This is especially useful for hiding implementation details, auto generating proxies, etc. 

Advantages 

App/Software is easier to extend 
Adds Flexibility to your App. 
Helps to maintain the loose coupling of code. 
0

接口是爲你的類就像原型。它的目的是爲您的課程提供結構。

如果您的類正在實現任何接口,那意味着類必須聲明接口中定義的所有屬性(即方法)。它可以被認爲是形容詞到你的班級。

如果您有兩個類別,即EagleParrot。然後您應該創建一個名爲canFly的接口。現在鷹和鸚鵡可以飛,但它們飛行的方式可能不同。這就是爲什麼界面沒有聲明。

相關問題