It needs to be inside an executable block of code to be executed. Otherwise there's no way to know when to execute it.
It doesn't have to be a method. You can use other blocks, such as Static
blocks and Instance
blocks.
For example, if you want a code to be executed whenever the class is loaded by the ClassLoader, you can use a static block:
public class MyClass{
static{
System.out.println("MyClass loaded");
}
}
If you want a code to be executed whenever a new instance of that class is created, you can use and instance block:
public class MyClass{
{
System.out.println("New instance of MyClass created");
}
}
It's important to say that you can have as many of these blocks as you need, and they can appear anywhere in the class body. The Runtime system will guarantee that they are executed in the order that they appear in your class
See also: