如何在Java中使用此关键字?
Java中的this关键字主要用于引用该类的当前实例变量。它也可以用于隐式调用方法或调用当前类的构造函数。
给出了一个在Java中演示this关键字的程序,如下所示:
示例
class Student {
private int rno;
private String name;
public Student(int rno, String name) {
this.rno = rno;
this.name = name;
}
public void display() {
System.out.println("Roll Number: " + rno);
System.out.println("Name: " + name);
}
}
public class Demo {
public static void main(String[] args) {
Student s = new Student(105, "Peter Bones");
s.display();
}
}输出结果
Roll Number: 105 Name: Peter Bones
现在让我们了解上面的程序。
使用数据成员rno,名称创建Student类。构造Student()函数使用此关键字初始化rno和name,以区分局部变量和实例变量,因为它们具有相同的名称。成员函数display()显示rno和name的值。演示此代码段如下:
class Student {
private int rno;
private String name;
public Student(int rno, String name) {
this.rno = rno;
this.name = name;
}
public void display() {
System.out.println("Roll Number: " + rno);
System.out.println("Name: " + name);
}
}在该main()方法中,使用值105和“PeterBones”创建了Student类的对象s。然后display()调用该方法。演示此代码段如下:
public class Demo {
public static void main(String[] args) {
Student s = new Student(105, "Peter Bones");
s.display();
}
}热门推荐
1 狗狗下楼训练
3 狗狗训练头盔
6 狗狗训练机构
7 训练狗狗步骤
9 狗狗能训练
10 狗狗基本动作训练方法
11 怎么训练狗狗叼饭盆
12 狗狗一岁了还能训练吗
13 训练狗狗的
14 宁波狗狗训练
15 训练狗狗拉屎
16 教狗狗训练
17 狗狗要怎么训练上厕所
18 狗狗靠的训练