父类Person
package com.cheng.fuxi.Demo03; public class Person { public Person() { System.out.println("Person的无参执行了"); } protected String name = "PQC"; protected void print(){ System.out.println("Person" } }
子类Student
package com.cheng.fuxi.Demo03; public class Student extends Person { public Student() { //隐藏代码: 调用了父类的无参构造器 super();//调用父类的构造器,必须在子类构造器的第一行; System.out.println("Student的无参执行了"); } public void print(){ System.out.println("Student"); } public void test1(){ print(); this.print(); super.print(); } }
super注意事项:
-
(super)子类要调用父类的构造器,必须在子类构造器的第一行;
-
父类生成了有参构造器的话(父类生成有参构造器的话子类是无法调用无参构造器的),子类也必须要用有参构造器;
-
super只能出现在子类的方法或者构造方法中;
-
super 和 this 不能同时调用构造方法;
this关键字:
代表的对象不同:
this : 本身调用者这个对象
super : 代表父类对象的引用
前提:
this : 没有继承也能使用
super : 只能在继承条件才可以使用
构造方法:
this : 本类的构造
super : 父类的构造