Skip to content

创建对象步骤

  1. 分配对象空间,并将对象成员变量初始化。数字类型默认为 0,布尔类型默认为 false,引用类型默认为空。
  2. 执行属性值的显式初始化。
  3. 执行构造方法。
  4. 返回对象的地址给相关变量。

本质

this 的本质就是当前对象的内存地址,也可以理解为就是当前对象。

this 的用法

指定成员变量及方法

  1. 指定成员变量是指可以用 this 拿到对象的成员变量来进行运算。

    java
    public class Index {
        public static void main(String[] args) {
            Test obj = new Test(10.5);
            System.out.printf("计算前:%s\n",obj.money);
    
            obj.computed(5.1);
            System.out.printf("计算后:%s\n",obj.money);
        }
    }
    
    class Test {
        double money;
    
        public Test(double money) {
            this.money = money;
        }
    
        void computed(double money) {
            this.money -= money;
        }
    }
  2. 上面代码中,在构造方法中通过 this 给成员变量 money 初始化了值。在 computed 方法中,通过 this 修改了原本的成员变量 money。简单说 this 可以区分成员变量和局部变量。

调用构造方法

  1. 如果遇到构造方法重载时,可以直接使用 this 调用其他的构造方法。

    java
    public class Index {
        public static void main(String[] args) {
            Student stu1 = new Student(1001,"张三");
            Student stu2 = new Student(1002,"李四",21);
        }
    }
    
    class Student {
        int id;
        String name;
        int age;
    
        public Student(int id,String name) {
            this.id = id;
            this.name = name;
        }
    
        public Student(int id,String name,int age) {
            this(id,name);
            this.age = age;
        }
    }
  2. 代码第 19 行,通过 this 调用了 13 行定义的构造方法,这样在 18 行的构造方法里就不用在写 id 和 name 了。值得注意的是,在一个构造方法重载中,若使用 this 调用其他构造方法,必须把 this 这条语句写在方法的第一行,否则会报错。

static 方法

this 不能用在由 static 修饰的方法中。

基于 MIT 许可发布