[英]Sub-class not able to access the protected method of super-class when the reference is of type super-class
[英]How to access super class field without cast when it can be ensured that the type is the same as the sub class?
我有以下代碼。 我可以使用 generics 以某種方式訪問 class DjikstraNode
的方法doSomething
中的number
屬性嗎? 我可以確保列表edges
僅包含DjikstraNode
類型的項目。
public class Node {
protected List<Edge> edges = new ArrayList<>();
}
public class Edge {
public Node source;
public Node destination;
}
public class DjikstraNode extends Node {
public int number;
public void doSomething() {
System.out.println(((DjikstraNode)edges.get(0).source).number);
}
}
如果Edge
class 將始終只包含DijkstraNode
,那么您根本不需要泛型類型。 只需將source
和destination
更改為DijkstraNode
(如評論中提到的@markspace)。
但是如果你想讓它更靈活並與任何Node
實現一起工作,那么你需要將子類類型傳遞給 super class。 在下面的代碼中, Edge
class 被參數化並接受任何擴展Node
類型的類型(假設給定Node
object 中的source
和destination
字段始終具有相同的類型)。
public class Node<T extends Node> {
protected List<Edge<T>> edges = new ArrayList<>();
}
public class Edge<T extends Node> {
public T source;
public T destination;
}
public class DjikstraNode extends Node<DjikstraNode> { // typo in your code here: Dijkstra
public int number;
public void doSomething() {
System.out.println(edges.get(0).source.number);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.