© Adam L. Davis 2016

Adam L. Davis, Learning Groovy, 10.1007/978-1-4842-2117-4_8

8. Traits

Adam L. Davis

(1)New York, USA

Traits are like interfaces with default implementations and state. Traits in Groovy are inspired by Scala’s traits.

Those familiar with Java 8 know that it added default methods to interfaces. Traits are similar to Java 8 interfaces but with the added ability to have state (fields). This allows more flexibility, but should be treated with caution.

Defining Traits

A trait is defined using the trait keyword:

1   trait Animal {
2       int hunger = 100
3       def  eat() { println "eating"; hunger -= 1 }
4       abstract int getNumberOfLegs()
5   }

As this code demonstrates, traits can have properties, methods, and abstract methods. If a class implements a trait, it must implement its abstract methods.

Using Traits

To use a trait, you use the implements keyword . For example:

 1   class Rocket  {
 2       String name
 3       def  launch() { println(name + " Take off!") }
 4   }
 5   trait MoonLander {
 6       def land() { println("${getName()} Landing!") }
 7       abstract String getName()
 8   }
 9   class  Apollo  extends  Rocket implements  MoonLander {
10   }

So now you can do the following:

1   def  apollo = new  Apollo(name: "Apollo 12")
2   apollo.launch()
3   apollo.land()

This would generate the following output:

1   Apollo 12 Take off!
2   Apollo 12 Landing!

Unlike super-classes , you can use multiple traits in one class. Here is such an example:

1   trait Shuttle {
2       boolean canFly() { true }
3       abstract int getCargoBaySize()
4   }
5   class MoonShuttle  extends  Rocket
6       implements  MoonLander, Shuttle {
7       int getCargoBaySize() { 100 }
8   }

This would allow you to do the following:

1   MoonShuttle m = new  MoonShuttle(name: 'Taxi')
2   println "${m.name} can fly? ${m.canFly()}"
3   println "cargo bay: ${m.getCargoBaySize()}"
4   m.launch()
5   m.land()

And you would get the following output:

1   Taxi can fly? true          
2   cargo bay: 100
3   Taxi Take off!
4   Taxi Landing!
A426440_1_En_8_Figa_HTML.jpg Exercise

See what happens when you have the same fields or methods in two different traits and then try to mix them.

Summary

In this chapter, you learned about the following Groovy features:

  • What traits are, which is similar to Java 8 interfaces.

  • How to define a trait with fields and methods.

  • How you can use multiple traits in one class.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset