Thursday 23 July 2015

Variable Shadowing/Overriding : Java vs Groovy

As Groovy is really powerful and offers lots of features that makes life of a developer easy, it has become really popular and as it is "Java-like", learning curve from Java to Groovy is not very steep. As most fundamentals are same as Java, you just have to get familiar with Groovy offerings to do a certain thing that is quite laborious in Java.

For a Java developer moving to Groovy, there could be surprises, at times, in terms of what you expect(like Java) and what you get as output in Groovy. I am discussing one such use case here.

Let us consider a very simple use case - One parent class, one child class and a variable that is present in both.


If you execute this code in Java, output will be 10 and in case of Groovy it will be 50.

In Java, variables are bound to reference and only methods are overriden, but the case is not the same for variable in Groovy.

My initial thought was that using parent.a would ultimately call parent.getA() in Groovy as there are implicit getters and setters for all the variables. So I tried accessing the variable directly using parent.@a . Surprisingly this made no change in the output produced.

Still not sure whether this is actually a feature of Groovy or something that should be changed.

Would love to know more thoughts on this.. :)


No comments:

Post a Comment