Classes and objects are key concepts in object-oriented programming, and they are used in Groovy to organize code and create reusable structures. Here’s how to define classes and objects in Groovy:
1. Classes: Classes are defined using the `class` keyword followed by the class name and the class body in curly braces. The class body can contain fields, methods, and other nested classes. Here’s an example:
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: 30) person.sayHello()
In this example, we define a class called `Person` with fields for `name` and `age` and a method called `sayHello` that prints a greeting. We create an instance of the `Person` class and call the `sayHello` method on that instance.
2. Objects: Objects are instances of classes, and they are created using the `new` keyword followed by the class name and any constructor arguments in parentheses. Here’s an example:
class Rectangle { int width int height int getArea() { return width * height } } def rectangle = new Rectangle(width: 5, height: 10) println("The area of the rectangle is ${rectangle.getArea()}.")
In thisexample, we define a class called `Rectangle` with fields for `width` and `height` and a method called `getArea` that calculates the area of the rectangle. We create an instance of the `Rectangle` class and call the `getArea` method on that instance.
Objects can also have properties, which are similar to fields but can have additional behavior such as validation or calculation. Here’s an example:
class Circle { double radius double getArea() { return Math.PI * radius * radius } void setRadius(double radius) { if (radius <= 0) { throw new IllegalArgumentException("Radius must be positive.") } this.radius = radius } } def circle = new Circle() circle.radius = 5 println("The area of the circle is ${circle.getArea()}.") try { circle.radius = -1 } catch (IllegalArgumentException e) { println(e.message) }
In this example, we define a class called `Circle` with a property for `radius` and a method called `getArea` that calculates the area of the circle. We also define a setter method for `radius` that validates the input value and throws an exception if it is not positive. We create an instance of the `Circle` class, set the `radius` property, and call the `getArea` method to calculate the area of the circle. We also test the validation by tryingto set a negative radius value, which should throw an exception and print an error message.
Classes and objects are important concepts in Groovy programming, and they allow you to create reusable structures and organize your code in a modular way.