super和this我们在继承中经常用到,我们知道this指的是当前对象,但super是不是父类对象呢?
我们先来看一个例子
我们先创建一个Human类作为父类
public class Human {
private String name;
private int age;
public Human() {
}
public Human(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
创建一个Student作为继承Human的子类
public class Student extends Human{
private int stu_Num;
public Student() {
super();
}
public Student(String name, int age, int stu_Num) {
super(name, age);
this.stu_Num = stu_Num;
}
}
在写一个测试类:
public class Test {
public static void main(String[] args) {
//创建对象
Human human = new Human();
Student student = new Student();
Human human2 = new Student();
//判断是否是实例
System.out.println(human instanceof Human);
System.out.println(human instanceof Student);
System.out.println(student instanceof Human);
System.out.println(student instanceof Student);
System.out.println(human2 instanceof Human);
System.out.println(human2 instanceof Student);
}
}
我们看到的输出结果:
我们可以看到instanceof可以判断对象是不是类的实例化
这样我们就可以去验证this是不是当前对象,super是不是父类对象
我们到Student 类中去测试this:
public Student() {
super();
System.out.println(this instanceof Student);
System.out.println(this instanceof Human);
}
我们在测试类中写:
//创建对象
// Human human = new Human();
Student student = new Student();
// Human human2 = new Student();
我在Student的构造方法中加入判断,this指的是当前对象我们应该看到的结果应该是:
true
true
我们创建对象输出结果:
结果不出我们所料
我们在Student类中的无参构造方法中调用了父类Human的构造方法 ,所以在调用父类方法中的this就是我们子类中的super,所以我们可以在父类Human中的无参构造方法中去测试super所指的对象 ,我们注释掉Student类中的输出方法:
public Student() {
super();
// System.out.println(this instanceof Student);
// System.out.println(this instanceof Human);
}
在父类Human中的构造函数中写:
public Human() {
System.out.println(this instanceof Student);
System.out.println(this instanceof Human);
}
在测试方法中创建Student对象,如果super所指的是父类类型的对象那我们得到的结果应该是:
false
true
但我们输出的结果是:
由此我们可以得出:
this:当前对象---执行当前方法的对象
super:就是this---调用父类构造的时候不是创建了一个父类对象,而是借用一下父类构造来创建子类的对象