Translate

New Live Courses

🚀 *Gen AI Engineer Telugu (Production Focused)*
🗓️ *Date:* 30th Sept 2026, 07:00AM IST
📝 *Register Now!:*
https://www.vlrt.in/gr
👥 *Join WA Community:*
https://www.vlrt.in/gw
💡*Course Content:*
https://www.vlrt.in/ai
▶️ *Demo Videos:*
https://www.vlrt.in/gv

🚀 *Service now Admin/ Development (ITSM)FREE Demo in Telugu*
🗓️ *Date:* 30th Sept 2026, 08:00AM IST
📝 *Register Now!:*
https://www.vlrt.in/7r
👥 *Join WA Community:*
https://www.vlrt.in/7w
💡*Course Content:*
https://www.vlrt.in/7c
▶️ *Demo Videos:*
https://www.vlrt.in/7v

🚀 *Vulnerability Management Training Demo*
🗓️ *Date:* 30th Sept 2026, 09:00 AM IST
📝*Register Now!:*
https://www.vlrt.in/vr
👥 *Join Community:*
https://www.vlrt.in/cw
💡 *Course Content:*
https://www.vlrt.in/vc
▶️ *Demo Videos:*
https://www.vlrt.in/Vm

Friday, 1 October 2021

Exercise Operator Overloading in Groovy Scripting groovy training telugu 17

 Watch The Video

https://youtu.be/-3klvINPqrk

------------------------------------------------------------------------------------------------------

[Exercise] Operator Overloading
In this exercise we are going to learn how to implement operator overloading on our own classes.

Create a new script called AccountDemo.groovy
Create a class called Account
Create a property called balance of type BigDecimal and initialize it to 0
Create a property called type of type String
Create a deposit method that will add to the balance
Create a withdraw method that will subtract from the balance
no need for this to check if they have that amount available (keep it simple)
With that code in place the following lines should work
Account checking = new Account(type:"Checking")
checking.deposit(100.00)
Account savings = new Account(type:"Savings")
savings.deposit(50.00)

We know that the String class has on overloaded method called plus that allows us to concatenate 2 strings right? So how could we take that logic and make it so we can make the following lines work.

BigDecimal total = checking + savings
println total



//Coding 


@groovy.transform.ToString
class Account{
BigDecimal balance=0.0
String type
BigDecimal deposit(BigDecimal amount){
balance +=amount
}
BigDecimal withdraw(BigDecimal amount){
balance -=amount
}
BigDecimal plus(Account,account){
this.balance=account.balance
}
}
Account checking =new Account(type:"Checking")
checking.deposit(100.00)


Account saving =new Account(type:"Saving")
saving.deposit(50.00)

println checking
println saving



BigDecimal total= checking +saving
println total















No comments:

Post a Comment

Note: only a member of this blog may post a comment.