Groovy class inheritance polymorphism
In Groovy, a class is a custom data type that encapsulates data and methods. An object is an instance of a class and can use the methods and attributes defined within it.
The following example demonstrates how to define classes and objects in Groovy:
class Person {
String name
int age
void sayHello() {
println("Hello, my name is ${name}, and I am ${age} years old.")
}
}
def person = new Person(name: "Alice", age: 25)
person.sayHello()
In the example above, we define a class named Person with two attributes (name and age) and one method (sayHello), which is used to print personal information. Then, using the new keyword, we create an instance of the Person class and store it in the variable person. Finally, we invoke the sayHello() method on the person object to output its details.
Classes in Groovy support key object-oriented programming features such as inheritance and polymorphism. The following example illustrates these concepts:
class Animal {
void makeSound() {
println("The animal makes a sound.")
}
}
class Dog extends Animal {
void makeSound() {
println("The dog barks.")
}
}
class Cat extends Animal {
void makeSound() {
println("The cat meows.")
}
}
def animal1 = new Animal()
def animal2 = new Dog()
def animal3 = new Cat()
animal1.makeSound() // Outputs: "The animal makes a sound."
animal2.makeSound() // Outputs: "The dog barks."
animal3.makeSound() // Outputs: "The cat meows."
In the example above, we define an Animal class and two subclasses, Dog and Cat. The Animal class has a makeSound() method. Both Dog and Cat classes override this method to return different strings. Then, we create three distinct objects: one of type Animal, one of type Dog, and one of type Cat. We call the makeSound() method on each object respectively, resulting in different output messages.
Groovy also supports other key concepts from object-oriented programming, including accessor and modifier methods (getter and setter methods), static methods and attributes, abstract classes, and interfaces.