Java中构造函数是否具有返回值类型?


否,Java 中的构造函数没有任何返回值类型。

构造函数看起来像方法,但它不是。它没有返回类型,并且其名称与类名相同。它主要用于实例化类的实例变量。

如果程序员没有编写构造函数,编译器会自动编写构造函数。

示例

如果你仔细观察以下示例中的构造函数声明,它仅具有与类相似的构造函数名称和参数。它没有任何返回类型。

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);
   }
}

输出

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

更新于: 30-Jul-2019

4K+ 浏览量

启动你的 职业

通过完成课程获得认证

开始吧
广告
© . All rights reserved.