目录
1:this关键字(this和this())
1.1:this关键字(两种用法)
1:表示当前对象的引用
public class Demo2 {
private int id;
//调用对象返回自身,那个对象调用返回那个对象
public Demo2 add() {
this.id=4;//当前对象的属性
System.out.println("add方法");
id++;
return this;//this代指当前对象的引用
}
@Override
public String toString() {
return "Demo2{" +
"id=" + id +
'}';
}
public static void main(String[] args) {
Demo2 demo2 = new Demo2();
System.out.println(demo2);
System.out.println(demo2.add());//调用对象调用方法 返回此对象
}
}
结果输出:

2:表示类的当前对象的变量(主要在set和构造函数中)
public class Demo1 {
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id){
this.id=id;//set方法中的this关键字
}
public Demo1(int id, String name1) {
id = id; //构造方法中的this关键字 没有构造不了id的值
name = name1;//虽然没有 但是name1赋值给了name可以构造
}
@Override
public String toString() {
return "Demo1{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
public static void main(String[] args) {
Demo1 demo1=new Demo1(1,"郑州");
System.out.println(demo1);
}
}
结果演示:

1.2:this()方法 用来调用当前对象的构造方法
public class Demo3 {
private int id;
private String name;
public Demo3() {
this(1,"等待");//调用有参构造
}
public Demo3(int id,String name) {
this.id = id;
this.name=name;
//this(); this() this(实参)必须出现在构造方法的第一行,否则报错
}
@Override
public String toString() {
return "Demo3{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
public static void main(String[] args) {
Demo3 demo3=new Demo3();//无参构造
System.out.println(demo3);
}
}
结果展示:

2:super关键字(super和super())
1:super关键字:调用当前父类构造方法和父类属性
super.父类public属性 super.父类public方法
super() super(参数) 调用父类构造方法

结果:











