new Object { } Construct

Viewed 40254

In Java, the standard way to create an object is using

MyClass name = new MyClass();

I also often see the construct

new MyClass() { /*stuff goes in here*/ };

I've been looking online for a while and can't find a good explanation of what the second construct style does or how it does it.

Can someone please explain how and why you would use the second construct?

6 Answers

If you want to new a object by a protect constructor from another package, you can use:

new Foo() {};

otherwise you will get an access error. It equals anonymous subclass inherited from Foo class.

From jdk8 onwards you may have seen different syntax seems like creating an objects while using lambda expressions.

NOTE: Lambda expressions don't get translated into anonymous inner classes, they use invoke dynamic that was introduced in Java 7 to execute functional methods.

For Example:

public class LambdaSample {

    public static void main(String[] args) {
        //If implementation is only one statement then {} braces are optional
        Runnable oneLineImplRunnable = ()->System.out.println("This is one line lambda expression");
        //Multiple statements in the implementation then {} braces are mandatory
        Comparator<StudentTest> stdComparator = (StudentTest s1,StudentTest s2)->{
            if(s1.getFirstName().equals(s2.getFirstName())) {
                return s1.getLastName().compareTo(s2.getLastName());
            }else {
                return s1.getFirstName().compareTo(s2.getFirstName());
            }
        };
    }
}
Related