簡體   English   中英

如何在向下轉換后訪問基類方法?

[英]How to access base class method after downcasting?

這是一個Java Generics程序,它使用set(T t),get()和print(T t)方法實現自定義接口。

我使用的類稱為Animal。 它需要一個T參數(在本例中為String)並為動物命名。

我的問題是我無法訪問我的print函數中的任何Animal類方法。

Animal<String> a1 = new Animal();
a1.set("Mickey");

public void print(Object o) {
  Animal oAnimal = (Animal) o; //Downcasting from Object to Animal.

  System.out.println(o.get()); //not accessible, and I don't know how to make it accessible.
//I can only access the methods from Object, not my custom class called Animal.
}

你應該用

oAnimal.get()

因為那是Animal的例子。

請記住,您沒有修改o ,因此它將保留為Object

問題是你仍然試圖在o上調用方法, o仍然是Object類型(就變量的編譯時類型而言,這是編譯器所關心的)。

如果你在oAnimal上調用方法,那就沒關系:

System.out.println(oAnimal.get());

(您不能返回結果System.out.println不過,因為它是一個無效的方法。你也可以指定你的無效方法的返回值。)

請注意,這與泛型無關。 您可以使用String簡單地演示您的問題中的代碼:

Object o = "foo";
String text = (String) o;
System.out.println(o.length()); // Error; Object doesn't have a length() method
System.out.println(text.length()); // Prints 3

你的(編輯過的)問題確實展示了泛型的用法,但是你對Animal的強制轉換是對原始類型的強制轉換,所以將泛型遺漏排除在等式之外更簡單 - 編譯失敗的原因與Animal無關通用的。

暫無
暫無

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

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