Methods in Groovy
Groovy supports methods defined on class types.
Output:
In Groovy, methods are defined within classes. Unlike some other languages, Groovy doesn’t have a separate concept of “receiver types” for methods. Instead, methods are always associated with the class they’re defined in.
The area()
and perimeter()
methods are defined directly in the Rectangle
class. They can access the instance variables (width
and height
) directly.
In the main
part of the script, we create an instance of Rectangle
using Groovy’s convenient map-style constructor syntax. We then call the methods on this instance.
Groovy uses duck typing and doesn’t distinguish between calling methods on values or references. This is why we can call the same methods on both r
and rp
with the same results.
Groovy’s approach to object-oriented programming is more traditional compared to some other languages, but it offers a lot of syntactic sugar and dynamic features that make it very expressive and flexible.
Next, we’ll look at Groovy’s mechanism for defining interfaces, which are used to specify a set of methods that a class must implement.