我们是否可以直接在 Java 中的一个方法内调用构造函数?
构造函数 类似于方法,当创建类对象时会调用构造函数,通常用于初始化类的实例变量。构造函数的名称与其类相同,并且没有返回类型。
无需显式调用构造函数,这些构造函数会在实例化时自动调用。
Java 中的this 关键字是对当前类对象的引用。使用它,你可以引用类的字段、方法或构造函数。
因此,如果你需要显式调用构造函数,可以使用“this()”对其进行调用。
从方法中调用构造函数
不,你无法从方法中调用构造函数。唯一可以从另一个构造函数的第一行使用 “this()” 或 “super()” 调用构造函数的位置是。如果你尝试在其他位置显式调用构造函数,将会生成一个编译时错误。
示例
import java.util.Scanner;
public class Student {
private String name;
private int age;
Student(){}
Student(String name, int age){
this.name = name;
this.age = age;
}
public void SetValues(String name, int age){
this(name, age);
}
public void display() {
System.out.println("name: "+this.name);
System.out.println("age: "+this.age);
}
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the name of the student: ");
String name = sc.nextLine();
System.out.println("Enter the age of the student: ");
int age = sc.nextInt();
Student obj = new Student();
obj.SetValues(name, age);
obj.display();
}
}编译时错误
Student.java:12: error: call to this must be first statement in constructor this(name, age); ^ 1 error
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP