关键字 :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);
}
}