Sudeep Kumar Das

Can we call a constructor from method in Java?

Interview Question Bank

Answer in Short

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

Explanation

1195    0

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


Share:   

More Questions from Interview Question Bank Module 0