簡體   English   中英

Java 使用接口作為數據類型

[英]Java using interface as data type

是否可以訪問 class object 的字段或 function 使用接口 ZA8CFDE633119EB2AC96B8 實現接口?

例如:

public interface Node { // reference to all my trucks

    void collect(Package p);
    void deliver(Package p);
    void work();

}

public class Truck implements Node{...} 
public class Van extends Truck {...}

public class Tracking {

    private Node node;

    @Override
    public String toString() {
        return "time:" + time + " " + node + ", status=" + status;
    }
}

And from another class I try to print Tracking and get node to be specific function from Van class but instead the node return only the toString of the van function. 而且我無法使用其他功能。

    for (int i = 0; i < this.tracking.size(); i++) {
        System.out.println(this.tracking.get(i));
    }

訪問 truckID 字段的主要問題

在此處輸入圖像描述

我將不勝感激有關如何解決此問題的解釋。

可以使用instanceof找到object的真正的class,能夠使用它的具體方法

for (Tracking track : this.tracking) {
    if (track instanceof Van){
        Van v = (Van) track;
        v.methodOfVan();
        System.out.println(v.truckID);
    }
    else if (track instanceof Truck ){ // For any other Truck that isn't Van
        Truck t = (Truck) track;
        t.methodOfTruck();
        System.out.println(t.truckID);
    }
}

您在這里使用 inheritance。 節點是超級class。 在您的代碼中,您有一個 Node 實例。 該節點實例可以分配給任何子類變量,例如 Van object。

您的問題是為什么在 Node 變量中沒有 van 特定的方法。 在編譯時查看,Java 編譯器不會知道將分配給 Node 變量的子類類型。 假設您有一輛出租車 class,就像 Van。 因此,可以將出租車 object 分配給節點 class。 由於編譯器無法使用此運行時信息,因此它將確保 Node 變量只能訪問 Node 特定字段。

如果您知道只有 Van 可以分配給 Node 變量,您可以進行顯式轉換。

Van van = (Van) node;

然后,您可以訪問 van 特定的字段或方法。 編譯器不會在這里抱怨,因為編碼器已明確處理 class 轉換,因此責任在於編碼器。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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