eRaisedToX eRaisedToX - 3 months ago 9
Java Question

What is meant by putting curly braces { } after a call to constructor in java

I dont really understand the purpose of empty curly braces placed in creating an instance of a class.

Here in line marked as line of doubt (3rd last line of code) ,what is the purpose of placing {} after new Bar()

public class Test
{
Test()
{
System.out.print("foo");
}

class Bar
{
Bar()
{
System.out.print("bar");
}
public void go()
{
System.out.print("hi");
}
}

public static void main (String [] args)
{
Test f = new Test();
f.makeBar();
}
void makeBar()
{
(new Bar(){}).go();// line of doubt
}
}

Answer

By putting curly braces after the new Bar() call, you're basically creating an anonymous extension of the Bar class and instantiating it. Inside those curly braces, you could override any of Bar's protected or public, non-final methods if you wanted to. Also, if Bar were an abstract class with no abstract methods and a no-arg constructor, you could instantiate one in this manner. If it had abstract methods, you would be required to override them inside the curly braces.

All that being said, the Bar class you have defined is neither abstract nor has any abstract methods, so instantiating an anonymous extension of it in this manner isn't any more useful than just calling the no-arg constructor without the empty curly braces.