1

In the Groovy delegation article here (http://groovy.codehaus.org/Delegate+transformation), I am confused by the following code:

After outlining:

import java.text.SimpleDateFormat

class Event {
    @Delegate Date when
    String title, url
}

def df = new SimpleDateFormat("yyyy/MM/dd")

def gr8conf = new Event(title: "GR8 Conference",
                          url: "http://www.gr8conf.org",
                         when: df.parse("2009/05/18"))
def javaOne = new Event(title: "JavaOne",
                          url: "http://java.sun.com/javaone/",
                         when: df.parse("2009/06/02"))

assert gr8conf.before(javaOne.when)

The article explains that the following can be used:

class Event extends Date {
    @Delegate Date when
    String title, url
}

However, in this following example, is it not redundant to have both inheritance and composition (delegation) especially in the context of "Prefer composition over inheritance?" ? Also, how does this not create a conflict (i.e. which methods are "delegated" to the delegate Date and which are called to the Date class from which the event inherits?

4

1 回答 1

2

Isn't the difference, that the first one delegates to Date methods but as it doesn't extend Date it can't be sent to a method that takes a Date parameter.

By adding the extends Date, you avoid this limitation

于 2013-06-22T18:46:34.070 回答