Showing posts with label Initializer Blocks. Show all posts
Showing posts with label Initializer Blocks. Show all posts

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

Friday, 21 February 2014

final variables

final is used to create two types of constants
    1. Creating final constants
    2. Creating final reference variables

1. Creating final constants.
Below post discussed about the final constants
http://selflearningjava.blogspot.in/2014/02/keyword-final.html

2. Creating final reference variables
When you assign an object to final reference variable, then the reference variable points to the same object, the object can change its state, I.e, its values. Assigning some other object or reference to the final reference variable is not allowed.

Example
class FinalReferenceEx{
  int width, height;

  public static void main(String args[]){
    final FinalReferenceEx ref1 = new FinalReferenceEx();

    ref1.width = 100;
    ref1.height = 200;
    System.out.println("Width is " + ref1.width + " height is " + ref1.height);

    ref1.width = 200;
    ref1.height = 300;
    System.out.println("Width is " + ref1.width + " height is " + ref1.height);
  }
}
   
Output
Width is 100 height is 200
Width is 200 height is 300

As you observe the output, the final reference variable is allowed to change the properties of the object that it is pointing. But it is not allowed to refer other object.

Example
class FinalReferenceEx{
  int width, height;

  public static void main(String args[]){
    final FinalReferenceEx ref1 = new FinalReferenceEx();

    ref1.width = 100;
    ref1.height = 200;
    System.out.println("Width is " + ref1.width + " height is " + ref1.height);

    ref1.width = 200;
    ref1.height = 300;
    System.out.println("Width is " + ref1.width + " height is " + ref1.height);

    ref1 = new FinalReferenceEx();
  }
}

I am trying to assign a new object to the final reference variable ref1, which is not acceptible, so compiler throws below error.

FinalReferenceEx.java:16: error: cannot assign a value to final variable ref1
ref1 = new FinalReferenceEx();
^
1 error

The same applicable for Arrays also, since Arrays also reference types.

Some Points to Remember

1. If a final variable holds a reference to an object, then the state of the object may be changed by operations on the object, but the variable will always refer to the same object.

2. What is blank final variable in Java ?
Blank final variable in Java is a final variable which is not initialized while declaration, instead they are initialized on constructor or initializer blocks or static initialization blocks.

Related Links

final keyword                                                 final classes and methods                                                 Home

Sunday, 9 February 2014

keyword : final

final is used to define constants. The final modifier indicates that the value of this field cannot change.

Defining class level constants
Declare the field with final and static combination

Example
class Person{
 static final int MAX_SALARY = 10000000;
 public static void main(String args[]){ 
  System.out.println(Person.MAX_SALARY);        
 }
}
       
Output
10000000
   
Defining Object level constants
    Declare the field with final keyword.

   Example
class Person{
 final int MAX_SALARY;

 Person(){
  MAX_SALARY = 10000;
 }

 Person(int sal){
  MAX_SALARY = sal;
 }

 public static void main(String args[]){
  Person p1 = new Person(1000000);
  System.out.println(p1.MAX_SALARY);
 }
} 

Output
 1000000 
   
Some Points to Remember
1. You must initialize the static final variables, other wise compiler throws the error
Example
class Person{
 final static int MAX_SALARY;
 public static void main(String args[]){
  System.out.println(Person.MAX_SALARY);
 }
}
  

When you try to compile the above program, compiler throws below error
Person.java:1: error: variable MAX_SALARY might not have been initialized
class Person{
^
1 error

This is not the case with non final variables.
Example
class Person{
 static int MAX_SALARY;
 
 public static void main(String args[]){
  System.out.println(Person.MAX_SALARY);
 }
}

Output    
0
          
2.Static final variables must be initialized at the time of creation or in the static block, Otherwise compiler throws error
class Person{
 static final int MAX_SALARY;
 
 static{
  MAX_SALARY = 1000000;
 }
 
 public static void main(String args[]){
  System.out.println(Person.MAX_SALARY);
 }
}
  
Output
1000000
   

Above program compiles and runs fine, since initializing the static final variable in the static block is completely fine.

3. Trying to initialize the static final variable other than at the time of creation or in static block cause the compile time error. 
Example
class Person{
 static final int MAX_SALARY;
 
 Person(){
  MAX_SALARY = 1000000; //is a static final, can't be initialized here
 }
 
 public static void main(String args[]){
  System.out.println(Person.MAX_SALARY);
 }
}
        
 When you try to compile the above program, compiler throws the below error
Person.java:5: error: cannot assign a value to final variable MAX_SALARY
MAX_SALARY = 1000000;
^
1 error

4. You must initialize the final variables whether those are static or non-static, otherwise compiler throws error
class Person{
   final int MAX_SALARY;
   public static void main(String args[]){
   }
}


When you tries to compile the program, Compiler throws below error
Person.java:1: error: variable MAX_SALARY might not have been initialized
class Person{
^
1 error
                           
5. Final instance variables must be initialized in the constructor or in the instance blocks.
Example 1
class Person{
 final int MAX_SALARY;
 Person(){
  MAX_SALARY = 10000;
 }
}
     
Example 2  
class Person{
 final int MAX_SALARY;
 
 {
  MAX_SALARY = 100000;
 }

 Person(){

 }

 void setSalary(){

 }
}

6. Trying to initialize final instance variables, other than in constructor causes compile time error.  

class Person{
 final int MAX_SALARY;

 Person(){
 }

 void setSalary(){
  MAX_SALARY = 100000;
 }
}
  

Compiler throws the below error
Person.java:8: error: cannot assign a value to final variable MAX_SALARY
MAX_SALARY = 100000;
^
1 error
 
7. final for Reference types: For references to objects, final ensures that the reference will never change, meaning that it always refer to the same object. It makes no guarantees whatsoever about the values inside the object being referred to staying the same.

8. How to declare global constants in Java ?
Make a variable as public static final.
                    


this keyword                                                 nested classes                                                 Home

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.

Example
class Box{
 int width,height;
 
 {
  width = 10;
  height = 15;
 }

 public static void main(String args[]){
  Box b1 = new Box();
  System.out.println(b1.width +"\t"+b1.height);
 }
}
      

Output
 10 15
      
Some Points to Remember
1. A class can have more than one initializer block
class Box{
 int width,height;
 String name;
 
 {
  width = 10;
  height = 15;
 }
 
 {
  name = "My Box";
 }

 public static void main(String args[]){
  Box b1 = new Box();
  System.out.println(b1.width +"\t"+b1.height);
  System.out.println(b1.name);
 }
}

Output
10 15
My Box

2. The data in initializer blocks copied to every constructor
Example
class Box{
 int width,height;
 String name;

 {
  width = 10;
  height = 15;
 }

 {
  name = "My Box";
 }

 Box(){

 }

 Box(int w){
  width = w;
 }
 
 public static void main(String args[]){
  Box b1 = new Box();
  Box b2 = new Box(100);
  
  System.out.println(b1.width +"\t"+b1.height);
  System.out.println(b1.name);
  System.out.println(b2.width +"\t"+b2.height);
  System.out.println(b2.name);
 }
}

Output
10 15
My Box
100 15
My Box


3. Initializer block are called every time, when you created the object
      Example  
class Person{
 {
  System.out.println("I am first");
 }

 {
  System.out.println("I am second");
 }

 public static void main(String args[]){
  Person p1 = new Person();
  Person p2 = new Person();
 }
}

Output
I am first
I am second
I am first
I am second

4. Initializing static fields in the initialization block is valid, but don't use it, since the static variable is initialized every time when a new object created.
Example
class Person{
 static int minSalary;
 
 {
  minSalary = 10000;
 }

 public static void main(String args[]){
  Person p1 = new Person();
  Person.minSalary = 50000;
  System.out.println(Person.minSalary);
  
  Person p2 = new Person();
  System.out.println(Person.minSalary);
 }
}

Output
50000
10000
      


Static Methods                                                 Static Blocks                                                 Home