Inheritance and polymorphism are key concepts in object-oriented programming, and they are used in Groovy to create hierarchical class structures and make code more flexible and reusable. Here’s how to use inheritance and polymorphism in Groovy:
1. Inheritance: Inheritance allows you to create a new class based on an existing class, inheriting all the fields, methods, and other features of the parent class while adding new or modified features. In Groovy, you can use the `extends` keyword to specify the parent class for a new class. Here’s an example:
class Animal { void sayHello() { println("Hello, I am an animal.") } } class Dog extends Animal { void sayHello() { println("Hello, I am a dog.") } } def animal = new Animal() animal.sayHello() def dog = new Dog() dog.sayHello()
In this example, we define a class called `Animal` with a method called `sayHello`, and a subclass called `Dog` that inherits from `Animal` and overrides the `sayHello` method to print a different message. We create instances of both classes and call the `sayHello` method on each instance, demonstrating the polymorphic behavior of the code.
2. Polymorphism: Polymorphism allows you to use objects of different classes interchangeably, as long as they share a common parent class or interface. In Groovy, you can use the parentclass or interface type as the variable type to achieve polymorphism. Here’s an example:
interface Shape { double getArea() } class Rectangle implements Shape { double width double height double getArea() { return width * height } } class Circle implements Shape { double radius double getArea() { return Math.PI * radius * radius } } def shapes = [new Rectangle(width: 5, height: 10), new Circle(radius: 5)] for (shape in shapes) { println("The area of the shape is ${shape.getArea()}.") }
In this example, we define an interface called `Shape` with a method called `getArea`, and two classes called `Rectangle` and `Circle` that implement the `Shape` interface and override the `getArea` method to calculate the area of the shape. We create a list of shapes containing instances of both classes, and then loop over the list and call the `getArea` method on each shape, demonstrating the polymorphic behavior of the code.
Inheritance and polymorphism are important concepts in Groovy programming, and they allow you to create hierarchical class structures and write flexible, reusable code. By using inheritance and polymorphism, you can create code that is easier to read, maintain, and extend.