关键字 this 和 super
this
:表示本类对象,调用方法时,表示当前方法的调用者作用:
调用本类的成员变量
调用本类的成员方法
调用本类的其他构造函数
public class Stu { String name; int age; double score; String address; String sex; double height; double weight; public Stu() { } public Stu(String name, int age,String sex) { this.name = name; this.age = age; this.sex = sex; } public Stu(String name, int age,double score,String address,String sex ,double height,double weight) { this(name, age, sex); this.address = address; this.height = height; this.weight = weight; this.score = score; } }
注:本类构造函数的调用必须是构造函数的第一条语句,this只能在非静态方法中使用,不可在静态方法和静态代码块中出现this关键字
super
:表示父类的引用作用:
调用父类的成员变量
调用父类的成员方法
调用父类的构造函数
注:
- 任何一个类的每一个构造函数中的第一行都默认调用了父类的无参构造函数
- 如果手动调用了父类的重载构造函数,那么就不再默认调用的父类无参构造函数了
- 父类构造函数的调用必须是子类构造函数中的第一条语句
- 构造函数中不能同时调用父类的构造函数和本类的构造函数;如果没有调用本类的构造函数,就在第一行默认调用父类的无参构造函数,如果调用了本类的构造函数,那么就不再默认调用父类的构造函数了
注意
:this和super关键字在调用构造函数的时候必须在调用方法的第一条语句,不可同时出现,否则报错.