While going through one of the library, I found the following construct in java which is really new for me. Assume there is a class Point in java.
class Point {
int x;
int y;
public Point() {}
public Point(int x, int y) {
this.x = x;
this.y = y;
}
}
While creating instance for Point, they initialize the variables x and y in the instance creation itself as below :
Point inst = new Point() {
{
this.x = 10;
this.y = 20;
}
};
Is this related to instance block in java or something different?
Your second example:
The syntax:
looks like an
Object, but is in fact creating a new object derived fromObject. The inner braces then declare the initialiser block.It’s a practise occassionally used to initialise collections e.g.
etc. One thing to note is that it’s an inner class and consequently there’s an implict reference to the outer (surrounding) class. Not normally a problem unless (say) you come to serialise this.