继承
- object类
- super - this
Application类:
package oop.demo06;
import oop.demo06.Student;
public class Application02 {
public static void main(String[] args) {
Student student = new Student();
/*
如果只有上面Student student = new Student();这句话,
输出: Person无参执行了
Student无参执行了
为什么只new了Student,会输出父类Person的东西,因为
有一句隐藏代码super();
*/
student.test("冰默");
System.out.println("--------------------");
student.test1();
}
}
输出:
Person类:
package oop.demo06;
public class Person {
public Person(String name) {
System.out.println("Person无参执行了");
}
protected String name = "LH";
//private私有的东西无法被继承,super也不行!
public void print(){
System.out.println("Person");
}
}
Student类:
package oop.demo06;
public class Student extends Person {
public Student() {
//隐藏代码:默认调用了父类的无参构造
super("name");//调用父类的构造器,必须要在子类构造器的第一行
System.out.println("Student无参执行了");
/*
如果父类中没有无参构造,设置了有参构造,那么子类也不能设置无参构造
一般父类设置了有参构造,都会显示的写出无参构造
如果执意要调用没有无参构造只有有参构造的的父类,就要显示的调用有参构造
如:super("name");
*/
}
private String name = "boom";
public void print(){
System.out.println("Student");
}
public void test1(){
print();//Student
this.print();//Student
super.print();//Person
}
public void test(String name){
System.out.println(name);//冰默
System.out.println(this.name);//boom
System.out.println(super.name);//LH
}
}
super注意点:
1.super调用父类的构造方法,必须在构造方法的第一个!
2.super必须只能出现在子类的方法或者构造方法中!
3.super 和 this 不能同时调用构造方法!
super和this对比:
代表的对象不同:
this:本身调用者这个对象
super: 代表父类对象的引用
前提
this:没有继承也可以使用
super:只能在继承条件下可以使用
构造方法
this();本类的构造
super();父类的构造
- 方法重写