Dasma
Dasma

Reputation: 1263

inheritance of variable in groovy

Maybe it is the late hours :) But can any one tell why parent class does pull variables from the child

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 

Upvotes: 0

Views: 637

Answers (1)

Will
Will

Reputation: 14519

There is no field inheritance in Groovy nor in Java. You can override the value of the field, as the linked question's answer suggest:

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"

Upvotes: 5

Related Questions