super
super注意点:
1.super调用父类的构造方法,必须在构造方法的第一个
2.super必须只能出现在子类的方法或者构造方法中!
3.super和this不能同时显示的调用有参构造方法!
VS this
代表的对象不同:
this: 本身调用者这个对象
super: 代表父类对象的应用
. 前提
this: 没继承也可以使用
super: 只能在继承条件下使用
构造方法
this(); 本类的构造
super(); 父类的构造
package com.oop.demo06;
public class Person {
public Person() {
//public Person(String name)
//父类一旦定义了有参,无参就没了,子类需显示的定义一个无参来调用父类的有参,若要调用父类的无参需在父类显示的定义一个无参!
System.out.println("person无参构造执行了");
}
protected String name = "帅哥";
//私有的东西无法被继承
public void print(){
System.out.println("小姐");
}
}
package com.oop.demo06;
public class Student extends Person{
public Student() {
//隐藏代码:调用了父类的无参构造
//调用父类的构造器必须要在子类构造器的第一行
//super();
//super("name")可以这样调用父类的有参!
this("hello");//调用本地有参!
System.out.println("子类的无参构造执行了");
}
public Student(String name) {
System.out.println(name);
}
private String name = "美女";
public void print() {
System.out.println("大哥");
}
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.oop;
import com.oop.demo06.Student;
public class Application {
public static void main(String[] args) {
Student student = new Student();
student.test("先生");
student.test1();
}
}