Groovy support operator overloading. For example, I am
going to show, how to override + and – operators to the custom class Box.
HelloWorld.groovy
class Box{ int width int height Box(int width, int height){ this.width = width this.height = height } Box plus(Box other) { int newWidth = this.width + other.width int newHeight = this.height + other.height return new Box(newWidth, newHeight) } Box minus(Box other){ int newWidth = this.width - other.width int newHeight = this.height - other.height return new Box(newWidth, newHeight) } void aboutMe(){ println "height : ${this.height}, width : ${this.width}" } } Box box1 = new Box(100, 120) Box box2 = new Box(50, 60) Box newBox1 = box1 + box2 Box newBox2 = box1 - box2 box1.aboutMe() box2.aboutMe() newBox1.aboutMe() newBox2.aboutMe()
Output
height : 120, width : 100 height : 60, width : 50 height : 180, width : 150 height : 60, width : 50
You can even overload the plus and minus methods to
support different data types.
Box
plus(int num){
int
newWidth = this.width + num
int
newHeight = this.height + num
return
new Box(newWidth, newHeight)
}
HelloWorld.groovy
class Box{ int width int height Box(int width, int height){ this.width = width this.height = height } Box plus(Box other) { int newWidth = this.width + other.width int newHeight = this.height + other.height return new Box(newWidth, newHeight) } Box plus(int num){ int newWidth = this.width + num int newHeight = this.height + num return new Box(newWidth, newHeight) } Box minus(Box other){ int newWidth = this.width - other.width int newHeight = this.height - other.height return new Box(newWidth, newHeight) } void aboutMe(){ println "height : ${this.height}, width : ${this.width}" } } Box box1 = new Box(100, 120) box1 = box1 + 11 box1.aboutMe()
Output
height : 131, width : 111
Below table summarize the operators and corresponding
methods supported by Groovy.
Operator
|
Method
|
+
|
a.plus(b)
|
-
|
a.minus(b)
|
*
|
a.multiply(b)
|
/
|
a.div(b)
|
%
|
a.mod(b)
|
**
|
a.power(b)
|
|
|
a.or(b)
|
&
|
a.and(b)
|
^
|
a.xor(b)
|
as
|
a.asType(b)
|
a()
|
a.call()
|
a[b]
|
a.getAt(b)
|
a[b] = c
|
a.putAt(b, c)
|
a in b
|
b.isCase(a)
|
<<
|
a.leftShift(b)
|
>>
|
a.rightShift(b)
|
>>>
|
a.rightShiftUnsigned(b)
|
++
|
a.next()
|
--
|
a.previous()
|
+a
|
a.positive()
|
-a
|
a.negative()
|
~a
|
a.bitwiseNegate()
|
No comments:
Post a Comment