this关键字的3种用法

本文详细介绍了this关键字在编程中的三个主要用途:一是用于在类的方法中区分属性与参数;二是作为当前对象引用调用同类中的其他方法;三是通过this()在构造方法中调用其他构造器进行初始化。

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

一、this.属性名

当一个类的属性(成员变量)名与访问该属性的方法参数名相同时,则需要使用 this 关键字来访问类中的属性,以区分类的属性和方法中的参数。

 

public class Teacher {
	//声明类的成员变量(属性)
	private String name;
	private double salary;
	private int age;
	
	//有参构造方法
	public Teacher(String name,double salary,int age){
		this.name = name;
		this.salary = salary;
		this.age = age;
	}
	
	public static void main(String[] args) {
		Teacher teacher = new Teacher("Yale", 10000, 24);
		System.out.println("The only phd teacher: ");
		System.out.println("Name:"+teacher.name+
				"\nSalary:"+teacher.salary+
				"\nAge:"+teacher.age);
	}

 

 

二、this.方法名

某个方法调用同一类中别的方法,不需要再创建对象,直接用this。

public class Dog {
	//jump方法
	public void jump(){
		System.out.println("JumpJumpJump");
	}
	
	//run方法
	public void run(){
		this.jump();
		System.out.println("run() had called jump().");
	}
	
	public static void main(String[] args) {
		Dog dog = new Dog();
		dog.run();

	}

三、this()访问构造方法

使用 this( ) 在构造方法中给 name 赋值。

public class Student {
	String name;
	
	//无参构造方法,使用 this( ) 在构造方法中给 name 赋值
	public Student(){
		this("Slender");
	}
	
	//有参构造方法
	public Student(String name){
		this.name = name;
	}
	
	//输出信息
	public void print(){
		System.out.println("Name:"+name);
	}
	
	public static void main(String[] args) {
		Student student = new Student();
		student.print();

	}

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值