也许是晚些时候:)但是任何人都可以告诉为什么父类会从孩子那里拉变量
Foo {
public String myString = "My test string of Foo"
public printOutString () {
println this.myString
}
}
Bar extends Foo {
public String myString = "My test string of Bar"
}
Foo.printOutString() //prints out "My test string of Foo" as expected
Bar.printOutString() //prints out "My test string of Foo" as not expected thought it would take the String from Bar instead
答案 0 :(得分:4)
Groovy nor in Java中没有字段继承。您可以覆盖字段的值,因为链接问题的答案提示:
class Foo {
public String myString = "My test string of Foo"
public printOutString () {
myString
}
}
class Bar extends Foo {
{ myString = "My Bar" }
}
assert new Foo().printOutString() == "My test string of Foo"
assert new Bar().printOutString() == "My Bar"