java中this关键字的使用

本文详细解释了Java中this关键字的三种主要用法:访问属性、调用成员方法以及在构造方法中调用其他构造方法。通过实例展示了未使用this可能导致的问题,并强调了正确使用this的重要性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

this的用法

  1)this.data; (访问属性)

  2)this.method; (访问方法)

  3)this(); (调用本类中其他构造方法)

1)this.data

public class Test {
    public static void main(String[] args) {
        Date date = new Date();
        date.setDate(2024, 3, 3);	// 设置 年、月、日
        date.printInfo();	// 打印 年、月、日
    }
}

class Date{
    public int year;
    public int month;
    public int day;

    public void setDate(int year, int month,int day){	// 设置 年、月、日
        year = year;
        month = month;
        day = day;
    }

    public void printInfo(){	// 打印 年、月、日
        System.out.println(year +" 年 " +  month + " 月 " + day +"日");
    }
}

输出结果:
在这里插入图片描述

原因:
  1)在 setDate() 方法中成员属性没有使用 this 标明,属性没有赋值且类型为 int 类型;

  2)int 型作为一个整型变量,默认初始化值为 0

  3)在调用setDate() 方法时,构造器中的属性被作为变量传入了方法,所以导致 year、month、day 全部为 0

// 在属性面前用 this 表明,就不会作为变量被传入方法
    public void setDate(int year, int month,int day){	// 设置 年、月、日
        this.year = year;
        this.month = month;
        this.day = day;
    }

此时输出结果:
在这里插入图片描述

2)this.method;

用来在成员方法中调用另一个成员方法

public class Test {
    public static void main(String[] args) {
        Cat cat = new Cat();
        cat.play();
    }
}

class Cat{
    public void play(){
        System.out.println("小猫正在玩耍...");
        this.eat();		// 在这里 this 调用了本类成员的 eat() 方法
    }
    
    public void eat(){
        System.out.println("小猫正在吃鱼...");
    }
}

输出结果:
在这里插入图片描述

3)this()

在构造方法中调用本类其他的构造方法

注意事项:
  1)this()必须放在第一行;( 所以不可以和 super() 共用 )

  2)一个构造方法只能调用一个构造方法,即只能存在一个 this() 。

public class Test {
    public static void main(String[] args) {
        Student jack = new Student();
    }
}

class Student{
    public String name;
    public int age;
    public char gender;

    // 有参构造器
    public Student(String name, int age, char gender) {
        this.name = name;
        this.age = age;
        this.gender = gender;
        System.out.println("有参构造器被调用...");
    }

    // 无参构造器
    public Student(){
        // 在无参构造器中调用有参构造器
        this("jack", 14, '男');
        System.out.println("无参构造器被调用...");
    }
}

输出结果:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值