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
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.
Joined: May 26, 2006
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.
Holla at me...<br /><a href="http://codeforfun.wordpress.com" target="_blank" rel="nofollow">http://codeforfun.wordpress.com</a>
Joined: May 26, 2006
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.
Joined: Feb 27, 2006
That's great. Thanks Clifton. I've added the "def" and it all works as expected.
Joined: Dec 12, 2006
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.