【补充学习系列】之 this 关键字个人理解方面:
this作用:
1.this代表所指向的调用者对象;
this作用详解:
1.this能够代表调用此方法(函数)的对象;
public void eat(){
System.out.println(this.name+":吃什么");//this代表调用了成员变量
}
2.this能够在构造方法中调用class内另外一个构造方法;
public Animal(String name ,String color){
//this.name=name;
this("狗");//调用下面的有参构造方法 "public Animal(String name){.......}"
this.color=color;
}
public Animal(String name){
this();//调用下面的无参构造方法 "public Animal(){....}"
this.name = name;
}
public Animal(){
}
this的调用问题:
1.this调用构造方法的时候应该放在方法内的第一句,不然会有错误产生;
public Animal(String name){
this.name = name;
this.();//这样是会报错,原因就在于this调用构造方法时需要在第一位;
}
2.this如果在一个构造方法a中调用另外一个构造方法b,在构造方法b中调用构造方法a这样就会造成死循环;
public Animal(String name ,String color){
this("狗");//调用下面的有参构造方法 "public Animal(String name){.......}" &&&&&死循环点1
this.color=color;
}
public Animal(String name){
this.("cat","red");//调用上面的有参构造方法 "public Animal(String name,String color){........}" &&&&&死循环点2
this.name = name;
}
this的一些注意:
1.存在同名的成员变量及局部变量时,在方法的内部访问的默认是局部变量(就近原则),可以通过this指定成员变量;
String name = "狗";//成员变量
public void eat(){
String name = "天鹅";//局部变量
System.out.println(name+":吃什么"); //此处默认调用的是局部变量,结果为天鹅。
}
2.如果在一个方法中访问了一个变量,该变量值存在成员变量的情况下,java编译器会在该变量的前面自动添加this关键字。
public void eat(){
System.out.println(name+":吃什么");//在cat对象调用eat()的时候,编译器会自动在name前面自动加上this(如下),因此输出的答案就为猫在吃,而不是null在吃;
//System.out.println(this.name+":吃什么");
}
public static void main(String[] args) {
Animal dog = new Animal("狗");
Animal cat = new Animal("猫");
cat.eat();//对象为:cat
}
//输出结果为:猫在吃;
3.过多使用this会造成读写困难,写的人明白这是调用什么,但是读的人就会阅读困难。