Show List

Object-Oriented Programming in Groovy

Object-Oriented Programming (OOP) is a programming paradigm that is based on the concept of objects, which are instances of classes. Objects contain both data and behavior, and they interact with each other to form a complete program.

Groovy is a dynamically-typed, object-oriented programming language that supports OOP features such as classes, objects, inheritance, encapsulation, and polymorphism.

Here are some examples of OOP in Groovy:

  1. Classes: Classes define the blueprint for creating objects, and they encapsulate the data and behavior associated with the objects.

Example:

javascript
Copy code
class Dog { String name int age void bark() { println("Bark!") } }
  1. Objects: Objects are instances of classes, and they represent the data and behavior defined in the class.

Example:

java
Copy code
def myDog = new Dog(name: "Buddy", age: 5) myDog.bark() // prints "Bark!"
  1. Inheritance: Inheritance is a mechanism that allows a class to inherit the properties and behavior of another class.

Example:

java
Copy code
class GoldenRetriever extends Dog { void fetch() { println("Fetching ball...") } } def myGoldenRetriever = new GoldenRetriever(name: "Max", age: 3) myGoldenRetriever.bark() // prints "Bark!" myGoldenRetriever.fetch() // prints "Fetching ball..."
  1. Encapsulation: Encapsulation is the mechanism of hiding the internal implementation details of an object and exposing only the necessary information to the outside world.

Example:

java
Copy code
class BankAccount { private double balance void deposit(double amount) { balance += amount } void withdraw(double amount) { if (balance >= amount) { balance -= amount } else { println("Insufficient funds.") } } } def myAccount = new BankAccount(balance: 1000.0) myAccount.withdraw(500.0) // withdraws 500.0 from the account println(myAccount.balance) // prints 500.0
  1. Polymorphism: Polymorphism is the ability of an object to take on many forms, and it enables an object to behave in different ways based on the context in which it is used.

Example:

scss
Copy code
class Animal { void makeSound() { println("Animal sound") } } class Dog extends Animal { void makeSound() { println("Bark!") } } def animal = new Animal() def dog = new Dog() animal.makeSound() // prints "Animal sound" dog.makeSound() // prints "Bark!"

These are the basic concepts of OOP in Groovy, and they can be used to write modular, reusable, and maintainable code.


    Leave a Comment


  • captcha text