Friday, 27 March 2020

Can an Anonymous class has an explicit constructor?

As per java specification, an anonymous class cannot have an explicitly declared constructor. Instead, a Java compiler must automatically provide an anonymous constructor for the anonymous class.

But what if you want some initialization code to be executed for an anonymous class.
You can execute initialization code using ‘Initializer Blocks’.

Initializer blocks are used to initialize instance variables.

Syntax of Initializer Blocks
{
         //initialization Blocks code goes here
}

Java compiler copies initializer blocks into every constructor.

App.java
package com.sample.app;

public class App {

 public static void main(String args[]) {
  Object obj = new Object() {

   {
    System.out.println("Inside Initializer Block 1");
   }

   {
    System.out.println("Inside Initializer Block 2");
   }
  };

 }

}

Output
Inside Initializer Block 1
Inside Initializer Block 2

Reference


You may like

No comments:

Post a Comment