Java中的继承和多态系列文章目录
第一章 super和this的使用区别
目录
一、super和this的使用方法
- 通过子类对象访问父类与子类不同的方法名和成员变量名时,优先在子类中寻找,找到则访问,其次才在父类中寻找
- 通过子类对象访问父类与子类相同的方法名和成员变量名时,就需要用到super和this,其中,super:访问父类成员,this:访问子类成员。如果不加,默认为子类方法或变量
public class Animal {
String name;
public void eat(){
System.out.println(name + " is eating!");
}
}
public class Dog extends Animal{
public String name;
public void method1(String name){
this.name = name + "son";
super.name = name + "parent";
}
public void eat(){
System.out.println(name+" is eating too!");
}
public void method(){
super.eat();
eat();//默认this
}
public void print(){
System.out.println(super.name);
System.out.println(name);
}
public Dog(){
this.name = "cute";
}
public static void main(String[] args) {
Dog dog = new Dog();
dog.method1("阿黄");
dog.method();
dog.print();
}
}
输出结果如下:
阿黄parent is eating!
阿黄son is eating too!
阿黄parent
阿黄son
注:super和this都只能在非静态方法中使用 !!!
二、this和super在构造方法中的使用
public class Animal {
String name;
public Animal(String name){
this.name = name;
}
public Animal(){
this("animal");
}
}
public class Dog extends Animal{
public Dog(){
//默认有super();
}
public Dog(String name){
super(name);
}
public static void main(String[] args) {
Dog dog1 = new Dog();
Dog dog2 = new Dog("dog");
System.out.println(dog1.name);
System.out.println(dog2.name);
}
}
输出结果如下:
animal
dog
对于dog1,我们并没写关于父类的构造方法,但是在构造子类对象时,会自动先执行父类构造的构造方法,再执行子类的构造方法(即先要将父类继承下来的成员初始化完整,然后再初始化自己的)。
注:
- 在子类构造方法中,使用super调用父类构造构造方法时,必须是子类构造方法的第一条语句
- super只能在一个子类构造方法中出现一次,且不能和this同时出现
三、super和this的异同
相同点:
- 都是Java中的关键字
- 都可以作为构造方法的第一条语句,且不能同时存在
- 只能在类的非静态方法中使用,用来访问非静态成员变量和方法
不同点:
- this是当前对象的引用,super是子类对象从父类继承下来的成员的引用
- this是非静态成员方法的一个隐藏参数,而super不是隐藏参数
- 成员方法中直接访问本类成员时,编译之后会将this还原;但在子类中如果通过super访问父类成员,编译之后在字节码层面super实际是不存在的
- 在构造方法中,一定会存在super的调用,用户没有写也默认存在,但this用户不写则没有