java this引用当前类的实例变量

this关键字可以用来引用当前类的实例变量。如果实例变量和参数之间存在歧义,则 this 关键字可用于明确地指定类变量以解决歧义问题。(更多教程请阅读码农之家)

了解没有 this 关键字的问题

下面先来理解一个不使用 this 关键字的示例:

class Student {
    int rollno;
    String name;
    float fee;

    Student(int rollno, String name, float fee) {
        rollno = rollno;
        name = name;
        fee = fee;
    }

    void display() {
        System.out.println(rollno + " " + name + " " + fee);
    }
}

class TestThis1 {
    public static void main(String args[]) {
        Student s1 = new Student(111, "ankit", 5000f);
        Student s2 = new Student(112, "sumit", 6000f);
        s1.display();
        s2.display();
    }
}

执行上面代码输出结果如下 -

0 null 0.0
0 null 0.0

在上面的例子中,参数(形式参数)和实例变量(rollnoname)是相同的。 所以要使用this关键字来区分局部变量和实例变量。

使用 this 关键字解决了上面的问题

class Student {
    int rollno;
    String name;
    float fee;

    Student(int rollno, String name, float fee) {
        this.rollno = rollno;
        this.name = name;
        this.fee = fee;
    }

    void display() {
        System.out.println(rollno + " " + name + " " + fee);
    }
}

class TestThis2 {
    public static void main(String args[]) {
        Student s1 = new Student(111, "ankit", 5000f);
        Student s2 = new Student(112, "sumit", 6000f);
        s1.display();
        s2.display();
    }
}

执行上面代码输出结果如下 -

111 ankit 5000
112 sumit 6000

如果局部变量(形式参数)和实例变量不同,则不需要像下面的程序一样使用this关键字:

不需要 this 关键字的程序示例

class Student {
    int rollno;
    String name;
    float fee;

    Student(int r, String n, float f) {
        rollno = r;
        name = n;
        fee = f;
    }

    void display() {
        System.out.println(rollno + " " + name + " " + fee);
    }
}

class TestThis3 {
    public static void main(String args[]) {
        Student s1 = new Student(111, "ankit", 5000f);
        Student s2 = new Student(112, "sumit", 6000f);
        s1.display();
        s2.display();
    }
}

执行上面代码输出结果如下 -

111 ankit 5000
112 sumit 6000

对变量使用有意义的名称是一种好的编程习惯。所以使用相同名称的实例变量和参数,并且总是使用this关键字。

posted @ 2021-12-14 09:40  small_123  阅读(139)  评论(0编辑  收藏  举报