I'm new to Java. Can anyone explain what happens in the main method??
class Demo {
public static void main(String []args) {
//setting a name using the constructor
Thread t=new Thread("main"){
//what is this? a static block?? need an explanation to this.
{setName("DemoThread");}
};
//output is DemoThread. Since it set the name again.
System.out.println(t.getName());
}
}
This line:
{setName("DemoThread");}
is called an initializer block (or instance initializer block). It looks like a static initializer block, but without the static keyword. It's useful for anonymous classes because they can't have named constructors. More details can be found here.
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