在groovy中继承变量

时间:2016-07-15 20:40:19

标签: grails groovy

也许是晚些时候:)但是任何人都可以告诉为什么父类会从孩子那里拉变量

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 

1 个答案:

答案 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"