在解释 this 和 super 的区别之前先说一下方法的重写 (Override) 和重载 (OverLoad)
- 方法的重写 (Override):在子类中,出现和父类一模一样方法声明的现象
public class Person
{
private String name;
private int age;
private String hobby;
public void show()
{
System.out.println("姓名:" + name + " 年龄:" + age + " 爱好:" + hobby);
}
}
public class Student extends Person
{
private int score;
public void show()
{
System.out.println("姓名:" + name + " 年龄:" + age + " 爱好:" + hobby + " 分数:" + score);
}
}
在子类 Student 类中声明了一个和父类 Person 类相同的 show() 方法,因此构成了方法的重写
- 方法的重载 (OverLoad):在本类中,出现方法名相同,参数列表不同的现象(跟返回值无关)
public class Student extends Person
{
private int score;
public void show()
{
System.out.println("姓名:" + name + " 年龄:" + age + " 爱好:" + hobby + " 分数:" + score);
}
public void show(int score)
{
System.out.println("姓名:" + name + " 年龄:" + age + " 爱好:" + hobby + " 分数:" + score);
}
}
在 Student 类中存在两个方法名同为 show 的方法声明,但是两个方法参数列表不同,因此构成了方法的重载
this 和 super
- this:本类数据的引用
this.变量名 调用本类的成员变量
this(..) 调用本类的构造方法
this.method(..) 调用本类的成员方法
public class Person
{
private String name;
private int age;
private String hobby;
public int num = 10;
public Person()
{
}
public Person(String name, int age)
{
this.name = name; //调用本类的成员变量
this.age = age;
}
public Person(String name, int age, String hobby)
{
this(name, age); //调用本类带两个参数的构造方法
this.hobby = hobby;
}
public void show()
{
System.out.prinltn("Person");
}
}
- super:代表存储空间的标识(可以理解为父类的引用)
super.变量名 调用父类的成员变量
super(..) 调用父类的构造函数
super.method(..) 调用父类的成员方法
public class Person
{
private String name;
private int age;
private String hobby;
public int num = 10;
public Person()
{
}
public Person(String name, int age)
{
this.name = name; //调用本类的成员变量
this.age = age;
}
public Person(String name, int age, String hobby)
{
this(name, age); //调用本类带两个参数的构造方法
this.hobby = hobby;
}
public void show()
{
System.out.prinltn("Person");
}
}
public class Student extends Person
{
private int score;
private int num = 20;
public Student(String name, int age, String hobby)
{
super(name, age, hobby); //调用父类的带参构造
}
public void method()
{
int num = 30;
System.out.println("Person的num" + super.num);//调用父类Person成员变量num = 10
System.out.println("Student的num" + this.num);//调用本类Student成员变量num = 20
System.out.println("method的num" + num);//调用method的局部变量num = 30
}
public void show()
{
super.show();//调用父类Person的show()方法
System.out.prinltn("Person");
}
}
注意:
1、在子类的构造方法中会默认调用父类的无参构造方法,这是因为子类继承了父类的成员,而且可能会用到父类的成员,所以需要调用父类无参构造对成员进行初始化。
2、子类调用父类构造函数时并不会创建父类对象,所以此时构造函数中的 this 实际上子类对象
3、this(..) 和super (..) 必须出现在第一条语句