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

  • 相关阅读:
    AcWing 37. 树的子结构
    AcWing 30. 正则表达式匹配 (剑指OFFER leetcode 10)
    Leetcode 514 自由之路
    AcWing 28. 在O(1)时间删除链表结点
    solrCloud+tomcat+zookeeper配置
    ZooKeeper原理及配置
    ZooKeeper原理及配置
    ZooKeeper原理及配置
    SolrCloud Hello Word
    SolrCloud Hello Word
  • 原文地址:https://www.cnblogs.com/impw/p/15397148.html
Copyright © 2011-2022 走看看