Java 继承②

发布时间:2026/7/23 0:53:38
Java 继承②
目录1. super 关键字2. super 和 this3. this和super访问时的内存布局1. super 关键字在父类成员变量和子类成员变量名字相同的情况下为了在子类中访问父类的成员。super关键字的用法 :super.父类成员变量classPerson{Stringname;intage10;publicvoidsleep(){System.out.println(name sleep );}}classPainterextendsPerson{intage20;publicvoidprint(){System.out.println(super.age);System.out.println(age);}}publicstaticvoidmain(String[]args){PainterpnewPainter();p.print();}super.父类成员方法classPerson{Stringname;intage10;publicvoidsleep(){System.out.println(Person:sleep);}}classPainterextendsPerson{publicvoidsleep(){System.out.println(Painter:sleep);super.sleep();}}publicstaticvoidmain(String[]args){PainterpnewPainter();p.sleep();}super ()调用父类构造方法super()只是帮助子类初始化继承父类的成员并没有创建父类对象。classPerson{Stringname;intage;publicPerson(Stringname,intage){this.namename;this.ageage;}}classPainterextendsPerson{booleanblindness;publicPainter(booleanblindness,Stringname,intage){super(name,age);this.blindnessblindness;}}publicstaticvoidmain(String[]args){PainterpnewPainter(true,da vinci,61);System.out.println( p.name p.age);System.out.println(blindness: p.blindness);}在初始化子类构造函数前需要给父类构造函数初始化。且super()必须要放在第一行。Error❌:注意在父类和子类都没有提供构造函数的情况下编译器会默认在子类和父类中生成隐含构造函数。所以在没写构造函数时并没有编译错误。classPerson{Stringname;intage10;publicPerson(){}}classPainterextendsPerson{booleanblindness;publicPainter(){super();}}this()和super()不能同时出现Error❌:classPerson{Stringname;intage10;publicPerson(Stringname,intage){this.namename;this.ageage;}}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.a10;super.b20;c30;this.d40;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){DeriveddnewDerived();d.method();}}