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
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP