这里我只创建了两个简单的类Dad
和Son
,Son是Dad的子类。
public class Dad {
}
public class Son extends Dad {
}
然后我在其他课程中创建一个Function
来测试
public class Test {
public static void main(String[] args) {
Function<? extends Dad, String> fun = son -> son.toString();
fun.apply(new Son());
}
但是我在fun.apply(new Son())
上遇到了一个编译器错误,它表示&#39; apply(功能中的captrue无法应用于(Son))&#39;。我很困惑,fun
需要一个扩展Dad
的类的参数,我给了子类但是根本不正确。
还有什么!我尝试new Dad()
作为fun
的参数,但也收到错误消息&#39; apply(功能中的captrue无法应用于(爸爸))&# 39;
最后,我不知道Function
具有通用版本时可以使用哪个参数。
帮助~~~ 谢谢! (⊙o⊙)
答案 0 :(得分:2)
请考虑以下事项:
class Daughter extends Dad {}
Function<Daughter, String> funcForDaughter = ...;
Function<? extends Dad, String> fun = funcForDaughter; // ok
fun.apply(new Son());
如果编译器允许您执行此操作,则可以将Son
传递给仅接受Daughter
的方法。同样的原因也禁止您致电fun.apply(new Dad())
。
Function<? extends Dad, String> fun
并不意味着fun
适用于Dad
的任何子类型。这意味着fun
适用于某些特定的Dad
子类型,此时此处未知。
通过这种方式声明fun
,除了fun.apply
之外,对null
以外的任何内容调用 @Component({
selector: 'test-app'
template:`
<h1>AngularJs 2 Material Design Demo</h1>
<md-input-container>
<label>Your name</label>
<input #newname />
</md-input-container>
<p (click)="test()" (focus)="test2()">
Hello, {{newname.value}}
</p>
`,
directives: [MdInputContainer, MdInput]
})
class TestApp {
constructor(){
this.title = 'AngularJs 2 Material Design Demo';
}
test() {
console.log('test');
}
test2() {
console.log('test2');
}
}
都是不安全的,因此编译器不会让你这样做。