在Java的构造函数中,我们能否调用“this”关键字的方法?
Java中的“this”关键字用作对当前对象的引用,在实例方法或构造函数中使用。使用this,您可以引用类的成员,例如构造函数、变量和方法。

从构造函数中使用this关键字调用方法
是的,如前所述,我们可以从实例方法或构造函数中调用类的所有成员(方法、变量和构造函数)。
示例
在下面的Java程序中,Student类包含两个私有变量name和age以及setter方法,还有一个接受这两个值的带参数的构造函数。
在构造函数中,我们通过分别向它们传递获得的name和age值,使用“this”关键字调用setName()和setAge()方法。
在main方法中,我们从用户读取name和age值,并通过传递它们来调用构造函数。然后,我们使用display()方法显示实例变量name和class的值。
public class Student {
private String name;
private int age;
public Student(String name, int age){
this.setName(name);
this.setAge(age);
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public void display(){
System.out.println("Name of the Student: "+this.name );
System.out.println("Age of the Student: "+this.age );
}
public static void main(String args[]) {
//Reading values from user
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();
//Calling the constructor that accepts both values
new Student(name, age).display();
}
}输出
Rohan Enter the age of the student: 18 Name of the Student: Rohan Age of the Student: 18
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP