Interfaces in Groovy
I'm about to start a social web app project.
While i开发者_StackOverflow中文版 was designing classes , i decided to define interfaces like "commentable" or "likeable" to use them when needed.
Yet i couldn't figure it out how to implement it in Groovy, that i am in the learning phase.
The Example below is from the Groovy documentation,
interface X
{ void f(); void g(int n); void h(String s, int n); }
x = [ f: {println "f called"} ] as X
x.f()
//x.g() // NPE here
Say this is one of my interfaces , and I want to use a Class called B to implement this interface ..
shall I just say B as X , in the related controller?
How to do it in domain layer? If a class Z is, lets say "commentable" , shall i just make a domain class called Comment and say Z hasMany Comment? and use the interface in the controller layer?
What is the Groovy way to do this correctly? I'm bit confused and a little clarification would be really nice.
Thanks in advance
The example you show is not the right one to use when implementing your own interfaces. That's a convenient way to only partially implement an interface. In this example only the f
method is implemented, so the others fail as you saw. This is useful for testing when you have a large interface but only call a few methods in the class under test, so you don't need to implement the whole interface.
You implement interfaces in Groovy just like in Java:
interface Math {
int add(int a, int b)
int multiply(int a, int b)
}
class SimpleMathImpl implements Math {
int add(int a, int b) {
a + b
}
int multiply(int a, int b) {
a * b
}
}
精彩评论