Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between {} and {{}} initialization in Java

Tags:

java

public class A{
}

A a = new A(){{
    final int x = 1; // IT HAS TO BE FINAL HERE. WHY?
}};

A aa = new A(){
    int x = 1; // THIS NEED NOT BE FINAL. WHY?
    final int y = 1; // STILL FINAL IS ALLOWED HERE. WHY?
    public int getX(){
        return x;
    }
};

Can somebody please answer the questions mentioned inside the snippet?

Thanks

like image 954
user855 Avatar asked Jun 25 '26 05:06

user855


2 Answers

The outer set of {} declares an anonymous subclass

The inner set declares an initialization block within that subclass.

With the following example, it becomes easier to understand what's going on:

List<String> strings = new ArrayList<String>() {{
    add("string");
    add("another string");
}};

You basically say: I want a subclass of List, which calls method add at initialization.

It's similar to:

List<String> strings = new ArrayList<String>();
strings.add("string");
strings.add("another string");
like image 122
Guillaume Avatar answered Jun 27 '26 08:06

Guillaume


A a = new A(){{
    final int x = 1; // IT HAS TO BE FINAL HERE. WHY?

It needn't.

The difference between the two is that in the first case, you're writing the code used to initialize each object in the double braces. That x is its local variable (doesn't have anything to do with objects of class A).

In the second case, you're defining the classes body. x would be its member variable. If it were static, its class variable. If final a (basically) constant.

like image 43
jpalecek Avatar answered Jun 27 '26 08:06

jpalecek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!