Super
-
super是调用父类的构造方法,必须在构造方法的第一个
-
super必须只能出现在子类的方法或者构造方法中
-
super和this不能同时调用构造方法
-
super和this代表的对象不同
- this:本身调用者这个对象
- super:代表父类对象的引用
super和this的前提不同
- this:没有继承也可以使用
- super:只能在继承条件下才能使用
super和this的构造方法不同
- this( ); 本类的构造
- super( ); 父类的构造
(1)子类引用父类protected的属性
package Demo05;
//父类:Person类
public class Person {
protected String name = "小陆同学";
}
package Demo05;
//子类:Student 是 父类Person的拓展
public class Student extends Person{
protected String name = "xiaolutongxue";
public void test(String name){
System.out.println(name); //输出传递的参数的值
System.out.println(this.name); //Student类(子类)的name
System.out.println(super.name); //Person类(父类)的name
}
}
package Demo05;
public class Application {
public static void main(String[] args) {
Student student = new Student();
student.test("小陆");
}
}
运行结果
(2)子类调用父类的一些方法
package Demo05;
//父类:Person类
public class Person {
public void print (){
System.out.println("Person");
}
}
package Demo05;
public class Student extends Person{
public void print(){
System.out.println("Student");
}
public void test1(){
print(); //调用Student类的print
this.print(); //调用Student类的print
super.print(); //调用Person类的print
}
}
package Demo05;
public class Application {
public static void main(String[] args) {
student.test1();
}
}
运行结果
(3)私有的属性无法被继承
(4)子类默认调用父类的无参构造
package Demo05;
//父类:Person类
public class Person {
public Person() {
System.out.println("Person无参执行");
}
}
package Demo05;
//子类
public class Student extends Person{
public Student() {
//隐藏代码:调用了父类的无参构造
super();
System.out.println("Student无参执行");
}
}
运行结果
(5)super( ); 调用父类构造器必须放在第一行
(6)this( ); 调用子类构造器也必须放在第一行
所以super( ); 和this( );不能同时调用构造方法
(7)只要重写了有参构造就得把无参构造加上去
父类
子类
那非要用有参构造,那子类就调用父类的有参构造就好了