• 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

  • 相关阅读:
    VS 2008 和 .NET 3.5 Beta 2 发布了
    搭建.NET 3.0环境
    Expression Studio和Silverlight学习资源、安装问题汇总
    Discuz! NT官方社区
    VS2005中ajax安装指南[转]
    IT人 不要一辈子靠技术生存(转)
    Discuz!NT2.5发布 正式版同步开源
    VS2005下开发Silverlight 1.1翻译加补充
    自动化测试案例
    [原]JavaScript必备知识系列开篇
  • 原文地址:https://www.cnblogs.com/impw/p/15397148.html
Copyright © 2020-2023  润新知