zoukankan      html  css  js  c++  java
  • this关键字

    this

    this是自身的一个对象,代表对象本身,可以理解为:指向对象本身的一个指针。

    1,当局部变量和成员变量重名的时候,在方法中使用this表示成员变量以示区分。

    class Demo{
        String str = "这是成员变量";
        void fun(String str){
            System.out.println(str);
            System.out.println(this.str);
            this.str = str;
            System.out.println(this.str);
        }
    }
    public class This{
        public static void main(String args[]){
            Demo demo = new Demo();
            demo.fun("这是局部变量");
        }
    }

    上面的类Demo中有一个成员变量str和一个局部变量str(类方法中的形式参数),很显然局部变量和成员变量重名,这个时候一般在方法中直接使用str实际上是使用局部变量str,对成员变量str没有任何影响,此时如果需要对成员变量做点什么,就必须使用this关键字。

    注意:如果在方法内部调用同一个类的另一个方法,就不必使用this。同样,在一个方法中如果没有局部变量和成员变量同名,那么在这个方法中使用成员变量也不必使用this

    class Demo{
        String str = "这是成员变量";
        void fun(String str1){
            System.out.println(str1);
            System.out.println(str);
        }
    }
    public class This{
        public static void main(String args[]){
            Demo demo = new Demo();
            demo.fun("这是局部变量");
        }
    }

    2,this关键字把当前对象传递给其他方法

    class Person{
        public void eat(Apple apple){
            Apple peeled = apple.getPeeled();
            System.out.println("Yummy");
        }
    }
    class Peeler{
        static Apple peel(Apple apple){
            //....remove peel
            return apple;
        }
    }
    class Apple{
        Apple getPeeled(){
            return Peeler.peel(this);
        }
    }
    public class This{
        public static void main(String args[]){
            new Person().eat(new Apple());
        }
    }

    Apple需要调用Peeler.peel()方法,他是一个外部的工具方法,将执行由于某种原因而必须放在Apple外部的操作为了将其自身传递给外部方法,必须使用this关键字。

    分析:假如各种水果去皮的工作都是一样的,只要给我水果,我都按同样的方法去皮。那么结合上面的例子,传进来一个水果,我们吃之前getPeeled(),必须将此水果作为参数传递给外部的peel(),用this来代表自身传递给外部方法。

    3,当需要返回当前对象的引用时,就常常在方法写return this;

    当你使用一个对象调用该方法,该方法返回的是经过修改后的对象,且又能使用该对象做其他的操作。因此很容易对一个对象进行多次操作。

    public class This{
        int i = 0;
        This increment(){
            i += 2;
            return this;
        }
        void print(){
            System.out.println("i = " + i);
        }
        public static void main(String args[]){
            This x = new This();
            x.increment().increment().print();
        }
    }结果为:4

     

  • 相关阅读:
    javaEE web 系统安装时自定义初始化
    windows 安装绿色版mysql
    myeclipse 安装svn(subeclipsesite)插件
    Xcode连接 Git
    生成16位不重复编码
    百度工程师也犯低级错误(有心还是无意)?
    IBatis 映射文件 sql 中大于、小于等符号转义
    web项目文档总览
    银行卡号的校验
    身份证的校验
  • 原文地址:https://www.cnblogs.com/qq1312583369/p/10922867.html
Copyright © 2011-2022 走看看