Java面向对象之关键字this

一: this关键字定义

  • 在Java中,this是一个特殊的引用变量,它引用当前对象本身。
  • 在类的内部,可以使用this来引用对象的当前实例的变量和方法

二:this关键字主要用途

2.1区分成员变量和局部变量
public class ThisExample {  
    private int x; // 成员变量  
  
    public ThisExample(int x) {  
        this.x = x; // 使用this引用成员变量x,并将参数x的值赋给成员变量x  
    }  
  
    public void printX() {  
        System.out.println("Value of x: " + this.x); // 使用this引用成员变量x  
    }  
}

2.2在构造方法中引用其他构造方法通过this()
package chapter6;

public class ThisExample {

    private int age;
    private int size;

    public ThisExample(int age){

        this(age,160);
    }

    public ThisExample(int age,int size){
        this.age = age;
        this.size = size;
    }

    public void printAge(){
        System.out.println("printAge方法的打印:"+ age);

    }

    public void printAgeAndSize(){
        System.out.println("printAgeAndSize方法的打印:" + age + "-----" + size);

    }

    public static void main(String[] args) {
        ThisExample thisExample = new ThisExample(10,170);
        thisExample.printAge();
        thisExample.printAgeAndSize();
    }
}


//运行结果
//printAge方法的打印:10
//printAgeAndSize方法的打印:10-----170

三:总结

  • this不能在静态方法中使用,因为静态方法不属于类的任何实例。
  • this引用的是当前对象的内存地址,而不是它的值。
  • this只能在构造方法或实例方法中使用,不能在类方法中(静态方法)使用。
  • 如果在构造方法中没有显式地使用this来调用另一个构造方法,则会自动调用无参数的构造方法(如果存在)
  • 但如果在构造方法中已经使用了this()来调用另一个构造方法,则不能再调用另一个构造方法或默认构造方法。
  • 9
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值