Does a constructor have a return type in Java?

Java 8Object Oriented ProgrammingProgramming

No, constructor does not have any return type in Java.

Constructor looks like method but it is not. It does not have a return type and its name is same as the class name. Mostly it is used to instantiate the instance variables of a class.

If the programmer doesn’t write a constructor the compiler writes a constructors on his behalf.

Example

If you closely observe the declaration of the constructor in the following example it just have the name of the constructor which is similar to class and, the parameters. It does not have any return type.

public class DemoTest{
   String name;
   int age;
   
   DemoTest(String name, int age){
      this.name = name;
      this.age = age;
      System.out.println("This is the constructor of the demo class");
   }
   public static void main(String args[]){
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the value of name: ");
      
      String name = sc.nextLine();
      System.out.println("Enter the value of age: ");
      
      int age = sc.nextInt();
      DemoTest obj = new DemoTest(name, age);
      
      System.out.println("Value of the instance variable name: "+name);
      System.out.println("Value of the instance variable age: "+age);
   }
}

Output

Enter the value of name:
Krishna
Enter the value of age:
29
This is the constructor of the demo class
Value of the instance variable name: Krishna
Value of the instance variable age: 29
raja
Published on 29-Dec-2017 09:06:39
Advertisements