• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Groovy and Polymorphism

 
James Leith
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi folks,
having come to Javaranch to look up some Jython information I encountered Groovy for the first time and thought I'd have a play with it. I have to say, as a java programmer it is much more intuitive than Jython and I like it a lot. The only problem I have encountered so far is that it doesn't appear to allow me to program to an interface.
I'm using Eclipse 3.1 and wrote something along the lines of

myInterface x;

x = new ParentClass();
x.printMessage();
x = new ChildClass();
x.printMessage();

Which resulted in the following error message "The name x does not refer to a declared variable or class."

ParentClass implements myInterface and ChildClass extends ParentClass and overrides printMessage().

When I cut and paste the code into a java project it compiled fine.

Changing the declaration to
ParentClass x=new ParentClass();
ChildClass y = new ChildClass();
made Groovy happy.


Am I doing something stupid or is this not supported by Groovy yet.

Thanks.
 
Clifton Craig
Ranch Hand
Posts: 103
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
From a brief look it appears you only need to declare the variable x in your code. That's what the error message is saying.
The following works for me right in GroovyConsole:


incidentally I could omit the def declaration from "x" and still run it in Groovy console because the rules for groovy "scripts" are slightly different than the rule for Groovy class definitions. In your case (in Eclipse) your specifying a Groovy class definition.
 
Clifton Craig
Ranch Hand
Posts: 103
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When writing a script you can omit declarations from the variable definitions, when you write a class the declarations are required. You need only declare a variable with the "def" keyword specifying types is optional in "script" files as well as Groovy class definitions.
 
James Leith
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That's great. Thanks Clifton. I've added the "def" and it all works as expected.
 
Tug Wilson
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I tried your example here and it works just fine (using Clifton's code and changing def to MyInterface).

Varables can be typed (i.e. declared as in Java ) or untyped (declared as def) in Groovy.

Java programers start by decaring everything as typed and then get comfortable with 'def' after a while (and with omitting ';').

Feel free to post any exception you get on the groovy usr list and we'll try and figure out your problem.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic