vvg
vvg

Reputation: 6385

How to override fields in groovy

class A {
    def p = 18
    def out() {
        println(p)
    }
}
class B extends A {
    def p = 21
}

new B().out()

I have the snippet as above. The output is ****.. Guess what?

My question is - how can I achieve results as it would be in java?

ps: groovy console works fine for those who wants execute sample above: groovyconsole.appspot.com

UPD : transforming property to method solves issue. any other options?

Upvotes: 2

Views: 1492

Answers (1)

bdkosher
bdkosher

Reputation: 5883

How about overriding the value of p in an initializer block?

class B extends A {
    { p = 21 }
}

Upvotes: 6

Related Questions