参考视频链接https://www.bilibili.com/video/BV1CJ411m7gg?p=53
this关键字
this 表示当前对象,可以调用类的属性、方法和构造器。
当在方法内需要用到调用该方法的对象时,就用this,用以区分对象和参数变量,提高程序可读性。
public class Person1 {
/**
* 在构造器中使用this()必须放在构造器的首行
* 使用this调用本类中其他的构造器,要保证至少有一个构造器是不用this的,否则会出现构造器自己调用自己的情况
*/
public Person1(){
}
public Person1(int age){
this();//调用无参数构造器方法
this.age=age;
}
public Person1(String name){
this(1);//调用参数为int age的构造器方法
this.name=name;
}
private String name;
private int age;
public Person1(String name,int age){
this.name=name;
this.age=age;
}
public void getInfo(){
System.out.println("姓名:"+name);
this.setAge();//调用当前类的方法
}
public void setAge(){
System.out.println("年龄:"+this.age);
}
public void setName(String name){
this.name=name;
}
public void setName1(String name){
this.setName(name);//调用setName方法,还是实现this.name=name;
}
}
重点都在注释里,手动狗头