How many ways are there to initialize the instance variables of a class in java?


You can initialize the instance variables of a class using final methods, constructors or, Instance initialization blocks.

Final methods

Whenever you make a method final, you cannot override it. i.e. you cannot provide implementation to the superclass’s final method from the subclass.

i.e. The purpose of making a method final is to prevent modification of a method from outside (child class). You can also use these final methods to initialize the instance variables.

Example

 Live Demo

import java.util.Scanner;
public class FinalMethods {
   int age = getAge();
   String name = getName();
   static Scanner sc = new Scanner(System.in);
   public static final int getAge() {
      System.out.println("Enter age value");
      return sc.nextInt();
   }
   public static final String getName() {
      System.out.println("Enter name value");
      return sc.next();
   }
   public void display(){
      System.out.println("Name and age values: ");
      System.out.println(this.name);
      System.out.println(this.age);
   }
   public static void main(String args[]){
      FinalMethods obj = new FinalMethods();
      obj.display();
   }
}

Output

Enter age value
25
Enter name value
Krishna
Name and age values:
Krishna
25

Constructors

A constructor is used to initialize an object when it is created. It is syntactically similar to a method. The difference is that the constructors have the same name as their class and, have no return type.

There is no need to invoke constructors explicitly these are automatically invoked at the time of instantiation.

Example

 Live Demo

public class Test {
   String name;
   int age;
   public Test(String name, int age){
      this.name = name;
      this.age = age;
   }
   public static void main(String args[]) {
      Test obj = new Test("Krishna", 25);
      System.out.println("Name: "+obj.name);
      System.out.println("Age: "+obj.age);
   }
}

Output

Name: Krishna
Age: 25

Instance initialization blocks

Similar to static blocks, Java also provides instance initialization blocks which are used to initialize instance variables, as an alternative to constructors.

Whenever you define an initialization block Java copies its code to the constructors. Therefore, you can also use these to share code between the constructors of a class.

Example

 Live Demo

public class Student {
   String name;
   int age;
   {
      name = "Krishna";
      age = 25;
   }
   public static void main(String args[]){
      Student std = new Student();
      System.out.println(std.age);
      System.out.println(std.name);
   }
}

Output

25
Krishna
raja
Published on 06-Sep-2019 17:31:45
Advertisements