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

  • 相关阅读:
    [poj_3469]多核CPU
    割点与桥,强连通分量,点双,边双[poj_1236]学校网络
    Iview 启动报错 TypeError [ERR_INVALID_CALLBACK]: Callback must be a function
    修改JAVA_HOME失效
    命令模式
    gradle implementation runtimeOnly 和api 区别
    spring boot 整合 RabbitMQ 错误
    关于技术的想法
    eclipse 背景绿豆沙颜色
    抽象工厂模式
  • 原文地址:https://www.cnblogs.com/impw/p/15397148.html
Copyright © 2011-2022 走看看