构造函数在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