Super详解
Super关键词
super学习时要与this区别开更好理解 在子类内部 调用父类的属性和方法是通过super关键词来实现的!
package com. yuecheng. oop. Demo05;
public class Student extends Person {
public Student ( ) {
super ( ) ;
System. out. println ( "子类的无参构造执行了" ) ;
}
private String name = "婉茹" ;
public void print ( ) {
System. out. println ( "Student" ) ;
}
public void test1 ( ) {
print ( ) ;
this . print ( ) ;
super . print ( ) ;
}
public void test ( String name) {
System. out. println ( name) ;
System. out. println ( this . name) ;
System. out. println ( super . name) ;
}
}
package com. yuecheng. oop. Demo05;
public class Person {
public Person ( ) {
System. out. println ( "父类Person无参构造执行了" ) ;
}
protected String name= "玥骋" ;
public void print ( ) {
System. out. println ( "Person" ) ;
}
}
package com. yuecheng. oop;
import com. yuecheng. oop. Demo05. Student;
public class Application {
public static void main ( String[ ] args) {
Student student = new Student ( ) ;
student. test1 ( ) ;
}
}
注意点
父类中私有的部分无法通过 super调用 super调用父类的构造方法,必须在构造方法的第一个。 super必须也只能出现在子类的方法或者构造方法中。 super和this 不能同时调用构造方法。
VS this
代表的对象不同:
this:本身调用这这个对象。 super:代表父类对象的引用。 前提
this:没有继承也可以使用。 super:只能在继承条件时才可以使用。 构造方法
this ()调用的 是本类的构造。 super(0调用的是父类的构造。