[英]If an class implements an interface, and is assigned to a variable with a type of that interface, what type is that object?
[英]Any object can be assigned in interface reference variable when class will implement these interface
當類將實現這些接口時,可以在接口引用變量中分配任何對象。
public interface MyInterface {
}
public class Test implements MyInterface {
public static void main(String[] args) {
Test test = new Test();
MyInterface myInterface = test;
}
這條線是什么意思?
MyInterface myInterface = test;
Interface
用作Type
。 這是使用Interface
的優點之一。 因此,我們可以擁有一個Interface
的Type變量,該變量可以引用implements
此Interface
任何實現。
最好的例子是Any Collection
Interface。
List<String> list = new ArrayList<String>();
在上面的示例中List
是接口,該變量指向實現List interface
ArrayList
。 說,在你想改變未來ArrayList
到LinkedList
,那么你必須改變只有一個字,它ArrayList
到LinkedList
。 所以看起來像
List<String> list = new LinkedList<String>();
還有一個好處是松耦合 。
變量有兩種類型:聲明(或靜態)類型和運行時類型。
變量
Test test = new Test();
被聲明為Test
類型,並且它引用的對象是運行時類型Test
。
這個變量
MyInterface myInterface = test;
聲明為MyInterface
類型,它引用的對象為Test
類型。
將對象的引用分配給某種超級類型的變量時,該對象實際上什么也沒有發生。 您將只能在變量上調用對該聲明的類型可見的方法。
讓我們嘗試畫它
Reference Object Reference
(Test) (Test) (MyInterface)
test -----------> actual object <----------- myInterface
將引用Test類對象的參考測試分配給已實現的接口MyInterface
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.