Here is my code:
class cat {}
class dog {
static void main(String[] args) {}
}
When compiled groovy says I do not have a main method. But when I get rid of the cat class:
class dog {
static void main(String[] args) {}
}
Its valid. I thought, as long as I had the main method in any class the code was valid, but I am wrong. Can someone explain why I can not have more than one class when the main method resides in one of the classes?
You can have more than one class, but the class defined first has to have the main method implementation. Normally when run as a script, the script is executed in run()
method.
In case you have a class defined, then the name of the class is used as the name of the script. In case there are more than one public class, then the runnable implementation has to be part of the first defined class. Below should work:
class Dog {
static void main(String[] args) {
println "hello"
}
}
class Cat {}
You can get a clear picture when you inspect AST in groovy console.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With