zoukankan      html  css  js  c++  java
  • Java this关键字初理解

    java this关键字

    可以用来引用当前类的实例变量。如果实例变量和参数之间存在歧义,则 this 关键字可用于明确地指定类变量以解决歧义问题。

    我基本理解为在构造方法中 this.what=what 为类中其他成员赋值

    下面先来理解一个不使用 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();
        }
    }
    

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

    0 null 0.0
    0 null 0.0
    

    Java
    在上面的例子中,参数(形式参数)和实例变量(rollno和name)是相同的。 所以要使用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();
        }
    }
    

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

    111 ankit 5000
    112 sumit 6000
    

    //原文出自【易百教程】,商业转载请联系作者获得授权,非商业请保留原文链接:https://www.yiibai.com/java/this-keyword.html

  • 相关阅读:
    SSD1963 低功耗应用
    LWIP UDP 协议分析
    CY22393的应用
    合并BIN文件的两种方法 转载
    STM32 PWM 互补输出函数 调试通过
    STM32 FSMC TFT LCD
    酷睿-家政保洁软件
    查询手机归属地
    折腾报表那些事儿(3) jatoolsprint
    table表格线条显示
  • 原文地址:https://www.cnblogs.com/impw/p/15397148.html
Copyright © 2011-2022 走看看