构造函数在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
热门推荐
10 舅舅大婚文案祝福语简短
11 新老师祝福语 简短独特
12 新年祝福语独创文字简短
13 水晶婚夫妻祝福语简短
14 给男生的简短祝福语
15 小孩想说的祝福语简短
16 爱小姨文案祝福语简短
17 姥爷生日祝福语简短精辟
18 英文写结婚祝福语简短