目录
- 1. super 关键字
- 2. super 和 this
- 3. this和super访问时的内存布局
1. super 关键字
在父类成员变量和子类成员变量名字相同的情况下,为了在子类中访问父类的成员。
super关键字的用法 :
super.父类成员变量
classPerson{Stringname;intage=10;publicvoidsleep(){System.out.println(name+" sleep ");}}classPainterextendsPerson{intage=20;publicvoidprint(){System.out.println(super.age);System.out.println(age);}}publicstaticvoidmain(String[]args){Painterp=newPainter();p.print();}super.父类成员方法
classPerson{Stringname;intage=10;publicvoidsleep(){System.out.println("Person:sleep");}}classPainterextendsPerson{publicvoidsleep(){System.out.println("Painter:sleep");super.sleep();}}publicstaticvoidmain(String[]args){Painterp=newPainter();p.sleep();}super ()调用父类构造方法
super()只是帮助子类初始化继承父类的成员,并没有创建父类对象。
classPerson{Stringname;intage;publicPerson(Stringname,intage){this.name=name;this.age=age;}}classPainterextendsPerson{booleanblindness;publicPainter(booleanblindness,Stringname,intage){super(name,age);this.blindness=blindness;}}publicstaticvoidmain(String[]args){Painterp=newPainter(true,"da vinci",61);System.out.println(" "+p.name+" "+p.age);System.out.println("blindness: "+p.blindness);}在初始化子类构造函数前,需要给父类构造函数初始化。且
super()必须要放在第一行。
Error❌:
注意:在父类和子类都没有提供构造函数的情况下,编译器会默认在子类和父类中生成隐含构造函数。
所以在没写构造函数时,并没有编译错误。
classPerson{Stringname;intage=10;publicPerson(){}}classPainterextendsPerson{booleanblindness;publicPainter(){super();}}
this()和super()不能同时出现
Error❌:
classPerson{Stringname;intage=10;publicPerson(Stringname,intage){this.name=name;this.age=age;}}classPainterextendsPerson{booleanblindness;publicPainter(Stringname,intage){super(name,age);}publicPainter(){super("p1",10);this("p2",15);}}2. super 和 this
相同点:
- 都是
Java关键字。 - 只能在类的非静态方法中访问非静态成员或方法。
- 在构造方法中,都必须放在第一行。
this()和super()不能同时出现。
不同点:
this是当前成员方法对象;super是当前成员方法对象中的父类部分。- 在非静态成员方法中,
this调用当前类的成员变量和方法;super调用继承父类的成员方法和成员。 - 在构造方法中,
this()调用当前类的构造方法;super()调用父类中的构造方法。 - 在构造方法中,一定会存在
super()的调用;用户不调用this(),就不存在。
3. this和super访问时的内存布局
classBase{inta;intb;publicvoidprint(){System.out.println("Base");}}classDerivedextendsBase{intc;intd;publicvoidmethod(){super.a=10;super.b=20;c=30;this.d=40;System.out.println(super.a);System.out.println(super.b);System.out.println(c);System.out.println(this.d);//this 访问子类和父类所有成员System.out.println(this.a);System.out.println(this.b);this.print();}}publicclassTest{publicstaticvoidmain(String[]args){Derivedd=newDerived();d.method();}}