Groovy Operators

Control Statements

Groovy File Handling

Groovy Error & Exceptions

Groovy Multithreading

Groovy Synchronization

Groovy - Trait Inheritance



A trait can inherit properties from other trait using extends keyword. In this way we can create a hiearchy of traits and can have fine grained control over trait compositions.

Syntax

trait Trait1 {}
trait Trait2 extends Trait1 {}

class MyClass implements Trait2 {}

Example - Traits Inheritance

In this example, we're creating a traits hiearchy using trait inheritance.

Create Trait as Base Trait

trait BaseLogger {
   void log(String message) {
      println "Log: ${message}"
   }
}

Create a sub trait

trait DateTimeLogger {
   void logWithTime(String message) {
      println new Date().toString()
	  log(message)
   }
}

Create a class implementing the sub-trait

Class MyReport implements DateTimeLogger {
   String title
   String content
   
   Report(String title, String content) {
      this.title = title
      this.content = content
   }

   void prepareReport() {
      logWithTime("Preparing report: ${title}")
      println "Report '${title}' prepared successfully."
   }
}

Use the Class

def salesReport = new MyReport("Daily Sales Details", "Total sales: $1000. Key products: TV, Mobile, Charger.")

salesReport.prepareReport()

Complete Example

Example.groovy

trait BaseLogger {
   void log(String message) {
      println "Log: ${message}"
   }
}

trait DateTimeLogger extends BaseLogger {
   void logWithTime(String message) {
      println new Date().toString()
	  log(message)
   }
}

class MyReport implements DateTimeLogger {
   String title
   String content
   
   MyReport(String title, String content) {
      this.title = title
      this.content = content
   }

   void prepareReport() {
      logWithTime("Preparing report: ${title}")
      println "Report '${title}' prepared successfully."
   }
}

def salesReport = new MyReport("Daily Sales Details", "Total sales: \$1000. Key products: TV, Mobile, Charger.")

salesReport.prepareReport()

Output

When we run the above program, we will get the following result.

Tue May 20 13:50:40 IST 2025
Log: Preparing report: Daily Sales Details
Report 'Daily Sales Details' prepared successfully.
Advertisements