java this调用属性和方法

关键字 :this

this用来表示当前对象。

this可以调用属性,方法,构造器。

this调用属性:
在构造器和方法中我们可以直接调用属性,往往会省略"this."。但是局部变量名和属性名一样时。
那么必须使用"this."来区分属性和局部变量。

this调用方法:
在同一个类中方法之间可以相互调用。在调用的时候可以省略 “this.”。

this调用构造器:

格式 : this(形参列表)
作用 :调用本类中的其它构造器

说明:

  • this(形参列表)必须在构造器的首行。
  • 在同一个构造器中最多只能有一个this(形参列表)
  • 如果有N个构造器那么最多只能有N-1个this(形参列表)
class Cat{

	String name;
	int age;
	
	//需求 :无论通过哪个构造器创建对象都必须输出一句"小龙哥真帅"
	public Cat(){
		System.out.println("Cat()");
		System.out.println("小A真帅");
	}
	
	public Cat(int age){
		this();
		System.out.println("Cat(int age)");
	}
	
	public Cat(String name,int age){
		this(age);
		System.out.println("Cat(String name,int age");
	}
	
	public void setName(String name){
		//思考 :使用的是局部变量还是属性? 局部变量 - 就近原则(局部变量名和属性名一样时用的是局部变量)
//		name = name;
		//this.name调用的是属性name
		this.name = name;
		//哪个对象调用的该方法,那么this就是那个对象
		System.out.println("this=====" + this);
	}
	
	public void test(){
		int a = 10;
		this.info();
		info(); //默认会加上"this."
	}
	
	public void info(){
		//调用属性时,默认会在属性的前面加上"this."
		System.out.println( this.name + " " + age);
	}
}

public class ThisTest {

	public static void main(String[] args) {

		Cat cat = new Cat();
		System.out.println("cat====" + cat);//输出的是对象的地址值
		cat.setName("小B");
		cat.info();
		
		System.out.println("-------------------------------------");
		
		Cat cat2 = new Cat();
		cat2.setName("大B");
		System.out.println("cat2====" + cat2);
		cat2.info();

		new Cat(20);
		new Cat("小猫咪",18);
		
	}
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

超级D洋葱

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值