Corporate Training
Request Demo
Click me
Menu
Let's Talk
Request Demo

Tutorials

Object-Oriented Programming in Groovy

13. Object-Oriented Programming in Groovy

Object-Oriented Programming (OOP) is a programming paradigm that organizes code into objects, which are instances of classes. Groovy is a powerful language that fully supports OOP principles, including encapsulation, inheritance, and polymorphism.

Classes and Objects:

In Groovy, classes are used to define the blueprint for objects. An object is an instance of a class and represents a real-world entity or concept.

Example: Defining a Class and Creating Objects
class Person {
    String name
    int age

    void sayHello() {
        println("Hello, my name is $name and I'm $age years old.")
    }
}

def person1 = new Person(name: "Alice", age: 30)
def person2 = new Person(name: "Bob", age: 25)

person1.sayHello() // Output: Hello, my name is Alice and I'm 30 years old.
person2.sayHello() // Output: Hello, my name is Bob and I'm 25 years old.
 

In this example, we define a 'Person'class with properties 'name' and 'age' and a method 'sayHello'. We then create two 'Person' objects and call the 'sayHello' method on each.

Encapsulation:

Encapsulation is the concept of bundling data (attributes) and methods (functions) that operate on that data into a single unit called a class. In Groovy, you can use access modifiers to control the visibility of class members.

Example: Encapsulation
class BankAccount {
    private double balance

    BankAccount(double initialBalance) {
        balance = initialBalance
    }

    void deposit(double amount) {
        if (amount > 0) {
            balance += amount
        }
    }

    double getBalance() {
        return balance
    }
}

def account = new BankAccount(1000)
account.deposit(500)
println("Current balance: ${account.getBalance()}") // Output: Current balance: 1500.0
 

In this example, the 'balance' property is encapsulated by marking it as 'private', and we provide public methods 'deposit' and 'getBalance' to interact with it.

Inheritance:

Inheritance is a mechanism that allows one class (subclass/derived class) to inherit properties and methods from another class (superclass/base class).

Example: Inheritance
class Animal {
    String name

    Animal(String name) {
        this.name = name
    }

    void speak() {
        println("$name makes a sound")
    }
}

class Dog extends Animal {
    Dog(String name) {
        super(name)
    }

    @Override
    void speak() {
        println("$name barks")
    }
}

def animal = new Animal("Generic Animal")
def dog = new Dog("Buddy")

animal.speak() // Output: Generic Animal makes a sound
dog.speak()    // Output: Buddy barks
 

In this example, the 'Dog' class inherits from the 'Animal' class and overrides the 'speak' method to provide a specific behavior.

Polymorphism:

Polymorphism allows objects of different classes to be treated as objects of a common superclass. It enables dynamic method invocation and method overriding.

Example: Polymorphism
class Shape {
    void draw() {
        println("Drawing a shape")
    }
}

class Circle extends Shape {
    @Override
    void draw() {
        println("Drawing a circle")
    }
}

class Square extends Shape {
    @Override
    void draw() {
        println("Drawing a square")
    }
}

def shapes = [new Circle(), new Square()]

shapes.each { shape ->
    shape.draw()
}
 

In this example, we create different shape objects (circles and squares) and store them in a list. We then iterate through the list and call the 'draw' method on each shape, demonstrating polymorphism.

Conclusion:

Object-Oriented Programming is a fundamental concept in Groovy and many other programming languages. By understanding classes, objects, encapsulation, inheritance, and polymorphism, you can create well-organized, maintainable, and extensible code in Groovy. These OOP principles help you model real-world entities and build complex applications with ease.