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

    this为一系统资源,只允许用户读而不允许写,它存放当前对象的地址(引用)。

    Java关键字this只能用于方法方法体内。当一个对象创建后,Java虚拟机(JVM)就会给这个对象分配一个引用自身的指针,这个指针的名字就是this。因此,this只能在类中的非静态方法中使用。并且this只和特定的对象关联,而不和类关联,同一个类的不同对象有不同的this。

        this变量有以下作用:

        1. 构造方法重用:

        public class Rectangle{
            public Rectangle(Location at, Shape size) {…}
            public Rectangle(Shape size,Location at){
                      this(at, size);

            }
            public Rectangle(Location at) {
                      this(at, new Shape(100,100));
            }
            public Rectangle(Shape size) {
                      this(size, new Location(1,1));
            }
            public Rectangle() {
                      this(new Location(1,1), new Shape(100,100));
            }
        }

        2、消除歧义:

        Location{
                 private int x;
                 private int y;
                 public Location(int x,int y)   {
                       this.x=x;
                       this.y=y;
                 }
        }

        3、返回对象-链式方法调用:

        public class Count {
        private int i = 0;
           Count increment() {
                    i++;
                    return this; //返回对象的地址,所以我们可以链式访问它
           }
           void print() {
                   System.out.println("i = " + i);
           }
        }


        public class CountTest{
               public static void main(String[] args) {
                    Count x = new Count();
                    x.increment().increment().print();
               }
        }

        4、作为参数传递"this”变量-进行回调:

        假设有一个容器类和一个部件类,在容器类的某个方法中要创建部件类的实例对象,而部件类的构造方法要接受一个代表其所在容器的参数。例如:
        class Container {
                 Component comp;
                 public void addComponent() {
                          comp = new Component(this); //代表你所创建的对象,因为它要用到.
                 }
        }


        class Component {
                 Container myContainer;
                 public Component(Container c) {
                          myContainer = c;
                 }
        }

  • 相关阅读:
    [转载] 美团-云鹏: 写给工程师的十条精进原则
    Docker测试一个静态网站
    Docker容器访问外部世界
    Docker容器间通信
    Docker网络(host、bridge、none)详细介绍
    Docker的资源限制(内存、CPU、IO)详细篇
    esxi中CentOS7不停机加磁盘并扩容现有分区
    ESXI6.5安装CentOS7教程
    Linux查看占用CPU和内存的 的程序
    Centos7使用脚本搭建LVS的DR模式。
  • 原文地址:https://www.cnblogs.com/delphione/p/2988363.html
Copyright © 2011-2022 走看看