[英]Define generic interfaces with same name but a different number of type parameters in Java
[英]Combining generic type parameters with interfaces in Java
與許多繼承問題一樣,我發現很難解釋我想要做什么。 但是一個快速(但奇特)的例子應該可以解決這個問題:
public interface Shell{
public double getSize();
}
public class TortoiseShell implements Shell{
...
public double getSize(){...} //implementing interface method
...
public Tortoise getTortoise(){...} //new method
...
}
public class ShellViewer<S extends Shell>{
S shell;
public ShellViewer(S shell){
this.shell = shell;
...
}
}
public class TortoiseShellViewer<T extends TortoiseShell> extends ShellViewer{
public TortoiseShellViewer(T tShell){
super(tShell); //no problems here...
}
private void removeTortoise(){
Tortoise t = tShell.getTortoise(); //ERROR: compiler can not find method in "Shell"
...
}
}
編譯器無法識別我想為getTortoise()
使用Shell的特定實現。 我哪里出錯了?
根據你在這里給出的,問題是:
public class TortoiseShellViewer<T extends TortoiseShell> extends ShellViewer
沒有正確指定ShellViewer
(通用)。 它應該是:
public class TortoiseShellViewer<T extends TortoiseShell> extends ShellViewer<T>
你要這個:
public class TortoiseShellViewer<T extends ToroiseShell> extends ShellViewer<T>
removeTortoise中的tShell是什么? 它是基類ShellViewer中Shell類型的實例嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.