我们可以在Java中使用此关键字调用方法吗?
Java中的“this”关键字在实例方法或构造函数中用作对当前对象的引用。是的,您可以使用它来调用方法。但是,您只能从实例方法(非静态)中调用它们。
示例
在下面的示例中,Student类具有一个私有变量名称,具有setter和getter方法,使用setter方法,我们已从main方法向name变量分配了值,然后,我们使用“实例方法中的“this”关键字。
public class ThisExample_Method {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void display() {
System.out.println("name: "+this.getName());
}
public static void main(String args[]) {
ThisExample_Method obj = new ThisExample_Method();
Scanner sc = new Scanner(System.in);
System.out.println("Enter the name of the student: ");
String name = sc.nextLine();
obj.setName(name);
obj.display();
}
}输出结果
Enter the name of the student: Krishna name: Krishna
热门推荐
1 训练狗狗工作
4 狗狗定点排便训练
5 狗狗训练吠叫
6 狗狗尿垫训练
7 狗狗训练座
8 狗狗训练攻略
9 狗狗训练记
10 做训练狗狗
11 狗狗训练词
12 狗狗谢谢怎么训练
13 狗狗训练如厕
14 狗狗太凶怎么训练
15 狗狗训练它
16 狗狗克制训练
17 训练基地狗狗
18 怎么样训练狗狗大小硬