Interfaces, traits and inheritance
Groovy has the single inheritance of Java, the interfaces of Java, and traits: a trait carries method bodies and fields, and a class may use several of them. The three cover three different needs.
An interface
shapes.groovy
interface Shape {
double area()
default String describe() {
String.format('%.2f', area())
}
}
class Square implements Shape {
double side
double area() {
side * side
}
}
def square = new Square(side: 3)
println square.area()
println square.describe()
groovy shapes.groovy
9.0
9.00
An interface declares a contract and may carry a default method, which is a Java 8 feature Groovy reads the same way. A field in an interface is a constant, and no interface holds state.
A trait
trait.groovy
trait Audited {
String createdBy = 'system'
String auditLine() {
"${getClass().simpleName} by ${createdBy}"
}
}
class Invoice implements Audited {
BigDecimal amount
}
class Receipt implements Audited {
BigDecimal amount
}
println new Invoice(amount: 10).auditLine()
println new Receipt(amount: 5).auditLine()
groovy trait.groovy
Invoice by system
Receipt by system
A trait is a class body that several classes may use: fields, methods and a this that is the class at run time. getClass() in the trait returns the using class, which is how one method serves two types.
An abstract class and super
abstract.groovy
abstract class Animal {
String name
abstract String sound()
String speak() {
"${name} says ${sound()}"
}
}
class Dog extends Animal {
String sound() {
'woof'
}
}
class Puppy extends Dog {
String sound() {
"small ${super.sound()}"
}
}
println new Dog(name: 'Rex').speak()
println new Puppy(name: 'Bit').speak()
groovy abstract.groovy
Rex says woof
Bit says small woof
An abstract class may hold fields and a partial implementation, and a subclass fills the abstract method. super.sound() calls the method of the parent, which is how a subclass extends behaviour instead of replacing it.
A class may implement several interfaces and use several traits, and inherit from one class. A trait method conflicts with a class method only when the class does not override it: the class wins, then the last trait, then the parent.
Related
- @Delegate, enums and visibility: composition instead of inheritance.
- Classes, properties and fields: the fields these types hold.
Автор статьи: Arthur Isaev