Groovy中变量的继承

Das*_*sma 0 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 
Run Code Online (Sandbox Code Playgroud)

Wil*_*ill 5

在Groovy 和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"
Run Code Online (Sandbox Code Playgroud)