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:
- Classes: Classes define the blueprint for creating objects, and they encapsulate the data and behavior associated with the objects.
Example:
javascriptCopy codeclass Dog { String name int age void bark() { println("Bark!") } }
- Objects: Objects are instances of classes, and they represent the data and behavior defined in the class.
Example:
javaCopy codedef myDog = new Dog(name: "Buddy", age: 5) myDog.bark() // prints "Bark!"
- Inheritance: Inheritance is a mechanism that allows a class to inherit the properties and behavior of another class.
Example:
javaCopy codeclass 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..."
- 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:
javaCopy codeclass 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
- 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:
scssCopy codeclass 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