zoukankan      html  css  js  c++  java
  • Java 中 this 的作用

    this 的作用就是用来区分类的成员变量和局部变量。

    我们来看下面这个例子:

    class Tmp {
        int x, y;
        Tmp(int x) {
            x = 4;
            y = 5;
        }
    }
    
    public class Main {
        static public void main(String[] args) {
            Tmp a = new Tmp(15);
            System.out.printf("%d %d
    ", a.x, a.y);
        }
    }
    

    输出了:0 5

    由于方法中局部变量屏蔽了成员变量,导致我们没让实例 a 的成员变量 x 成为 4。这个时候要想在方法中修改被屏蔽的成员变量,就要用到 this

    class Tmp {
        int x, y;
        Tmp(int x) {
            this.x = 4;
            y = 5;
        }
    }
    
    public class Main {
        static public void main(String[] args) {
            Tmp a = new Tmp(15);
            System.out.printf("%d %d
    ", a.x, a.y);
        }
    }
    

    像这样,我们就成功的将实例 a 的成员变量修改成了 4 5。

  • 相关阅读:
    http
    jquery
    wsgi
    urls控制器
    模板template
    ORM
    C++中获取汉字拼音首字缩写/全拼及生僻字的处理
    C语言函数strstr
    CString 成员函数用法
    判断字符串中是否存在中文
  • 原文地址:https://www.cnblogs.com/Node-Sans-Blog/p/13666414.html
Copyright © 2011-2022 走看看