
这一节复习一下this和super的使用,重点放在他们调用构造器上!
1.this可以用来修饰、调用:属性、方法、构造器
2.this修饰属性和方法:
this 理解为:当前对象或当前正在创建的对象
package this和super;
public class Demo {
String name;
int age;
public Demo() {
}
public Demo(int age){
// age = age; 错误写法!参数名和属性名相同,此时this不能省略
this.age = age;
}
public void print(String name){
// name = name 错误写法!参数名和属性名相同,此时this不能省略
this.name = name;
System.out.println("我是" + this.name);
}
}
3.this调用构造器
package this和super;
public class Demo {
private String name;
private int age;
// 无参的构造方法
Demo(){
System.out.println("无参的构造方法");
}
// 一个参数的构造方法
Demo(String n){
this();
this.name = n;
System.out.println("一个参数的构造方法");
}
// 两个参数的构造方法
Demo(String n,int a){
this(n);
this.age = a;
System.out.println("两个参数的构造方法");
}
void speak() {
System.out.println("我的名字是" + name + ",今年" + age + "岁");
}
}

调用属性和方法
1.我们可以在子类的方法或构造器中。通过使用"super.属性"或"super.方法"的方式,显式的调用父类中声明的属性或方法。但是,通常情况下,我们习惯省略"super ."
2.特殊情况:当子类和父类中定义了同名的属性时,我们要想在子类中调用父类中声明的属性,则必须显式的使用"super.属性"的方式,表明调用的是父类中声明的属性。
3.特殊情况:当子类重写了父类中的方法以后,我们想在子类的方法中调用父类中被重写的方法时,则必须显式的使用"super.方法"的方式,表明调用的是父类中被重写的方法。
4.super 调用构造器
父类Person.java
package this和super;
public class Person {
String name;
int age;
int id;
public Person() {
this.id = 11;
System.out.println("我是父类的空参构造!");
}
}
子类Student.java
package this和super;
public class Student extends Person{
int id; //属性不会被重写,不用担心会被覆盖掉,即这里的id和父类的id不同
public Student() {
//在构造器的首行,没有显式的声明"super(形参列表)",则默认调用的是父类中空参的构造!即super()
System.out.println("我是子类的空参构造!");
}
public Student(int id) {
super(); // 调用父类构造器
this.id = id;
System.out.println("我是子类的有参构造!");
System.out.println("父类id : " + super.id);
System.out.println("子类id : " + this.id);
}
public static void main(String[] args) {
Student stu1 = new Student();
Student stu2 = new Student(12);
}
}

如果你觉得博主写的还不错的话,可以关注一下当前专栏,博主会更完这个系列的哦!也欢迎订阅博主的其他好的专栏。
🏰系列专栏
👉软磨 css
👉硬泡 javascript
👉flask框架快速入门