Can we call a constructor directly from a method in java?


A constructor is similar to method and it is invoked at the time creating an object of the class, it is generally used to initialize the instance variables of a class. The constructors have 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.

The this keyword in Java is a reference to the object of the current class. Using it, you can refer a field, method or, constructor of a class.

Therefore, if you need to invoke a constructor explicitly you can do so, using "this()".

Invoking a constructor from a method

No, you cannot call a constructor from a method. The only place from which you can invoke constructors using “this()” or, “super()” is the first line of another constructor. If you try to invoke constructors explicitly elsewhere, a compile time error will be generated.

Example

import java.util.Scanner;
public class Student {
   private String name;
   private int age;
   Student(){}
   Student(String name, int age){
      this.name = name;
      this.age = age;
   }
   public void SetValues(String name, int age){
      this(name, age);
   }
   public void display() {
      System.out.println("name: "+this.name);
      System.out.println("age: "+this.age);
   }
   public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the name of the student: ");
      String name = sc.nextLine();
      System.out.println("Enter the age of the student: ");
      int age = sc.nextInt();
      Student obj = new Student();
      obj.SetValues(name, age);
      obj.display();
   }
}

Compile time error

Student.java:12: error: call to this must be first statement in constructor
   this(name, age);
       ^
1 error
raja
Published on 01-Aug-2019 15:41:06
Advertisements