super
super注意点:
1.super调用父类的构造方法,必须在构造方法的第一个
2.super必须只能出现在子类的方法或者构造方法中
3.super和this不能同时调用构造方法
super VS this
1.代表的对象不同:
this:本身调用者这个对象
super:代表父类对象的应用
2.前提
this:没有继承也可以使用
super:只能在继承条件才可以使用
3.构造方法
this():本类的构造
super():父类的构造
父类
package com.jiang.oop.Demo2;
public class Person {
protected String name="鲨鱼";
public Person() {
System.out.println("person无参构造执行了");
}
public Person(String name) {
System.out.println("person有参构造执行了");
}
public void print(){
System.out.println("Person");
}
}
子类
package com.jiang.oop.Demo2;
public class Student extends Person{
private String name="李小明";
public Student() {
//隐藏代码:super();//默认调用了父类的无参构造
super();//调用父类的构造器,必须要在子类构造器的第一行
// super("张三");
System.out.println("student无参构造执行了");
}
public Student(String name) {
this.name = 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.jiang.oop;
import com.jiang.oop.Demo2.Student;
public class Application1 {
public static void main(String[] args) {
Student student = new Student();
student.test("张三");
student.test1();
}
}