Java 中的this关键字

1.this关键字代表当前对象

  this.属性  操作当前对象的属性

  this.方法  调用当前对象的方法

2.封装对象的属性的时候,经常会使用this关键字

public class Telphone {
    private float screen;
    private float cpu;
    private float mem;
    
    public void sendMessage(){
        System.out.println("sendMessage");
    }
    
    public float getScreen() {
        return screen;
    }
    public void setScreen(float screen) {
        this.screen = screen; // 操作当前对象的属性
        this.sendMessage();      // 调用当前对象的方法
    }
    public float getCpu() {
        return cpu;
    }
    public void setCpu(float cpu) {
        this.cpu = cpu;
    }
    public float getMem() {
        return mem;
    }
    public void setMem(float mem) {
        this.mem = mem;
    }
    public Telphone(){
        System.out.println("com.imooc.Telphone");
    }
    public Telphone(float newScreen,float newCpu,float newMem){
        if(newScreen<3.5f){
            System.out.println("...............");
            screen = 3.5f;
        }
        cpu = newCpu;
        mem = newMem;
        System.out.println("----------------");
    }
}

this

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

this 的用法在 Java 中大体可以分为3种:

1.普通的直接引用

这种就不用讲了,this 相当于是指向当前对象本身。

2.形参与成员名字重名,用 this 来区分:

package s2;

class Person {
    private int age = 22;
    public Person() {
        System.out.println("初始化年龄:" + age);
    }
    
    public int getAge(int age) {
        this.age = age;  // 形参与成员名字重名
        return this.age;
    }
}

public class Test03 {
    public static void main(String[] args) {
        Person Harry = new Person();
        System.err.println("Harry's age is:" + Harry.getAge(33));
    }
}

运行结果:

初始化年龄:22
Harry's age is:33

3.引用构造函数

这个和 super 放在一起讲,见下面

扫描二维码关注公众号,回复: 2680221 查看本文章

猜你喜欢

转载自www.cnblogs.com/chuijingjing/p/9457601.html