Cedric Gatay
Cedric Gatay

Reputation: 1583

How to instantiate a Java abstract class with a constructor parameter with a groovy closure

I am trying to instantiate a Java abstract class from my Groovy code. Considering the following Java abstract class (non relevant processing is stripped out from the class):

public abstract class StackOverflow{
  public abstract String answerMe();
}

I can easily instantiate it in Groovy this way, and the call to answerMe() will trigger the correct output:

StackOverflow stack = [answerMe : { "Answer" }] as StackOverflow

Now if I modify the StackOverflow class adding a String parameter in the constructor like this :

public abstract class StackOverflowStr{
  public StackOverflowStr(String s){}
  public abstract String answerMe();
}

I don't really know how to instantiate my object, I tried a lot of thing, but I can't seem to find the right syntax, does someone got any clue ?

Upvotes: 6

Views: 4541

Answers (2)

Glen Best
Glen Best

Reputation: 23115

Just for the record, and to be clear on wording: in all of these scenarios, you're not instantiating an abstract class.

Abstract classes are classes that can never be instantiated.

You're instantiating a concrete anonymous class that extends an abstract class. B-)

Upvotes: 3

Andrea Parodi
Andrea Parodi

Reputation: 5614

You can instantiate it in classic Java style:

StackOverflowStr stack = new StackOverflowStr("javaish"){
    String answerMe() {"answer"}
}

Upvotes: 3

Related Questions