继承及super关键字
- 2022 年 2 月 23 日
- 筆記
继承
- 继承的本质是对某一批类的抽象,从而实现对世界更好的建模
- extend的意思是“扩展”,子类是父类的扩展。
- Java中类只有单继承,没有多继承;儿子只能有一个亲生爸爸,一个爸爸可以有多个儿子
- 继承是类与类之间的一种关系。除此之外还有依赖,组合,聚合等
- 继承关系的两个类,一个为子类(派生类),一个为父类(基类)。子类继承父类使用关键字extend
public class Person {
// public>protected>default>private
private int money=10000000;
public void say(){
System.out.println("说了一句话");
}
public int getMoney() {
return money;
}
public void setMoney(int money) {
this.money = money;
}
}
//学生 is 人 :派生类 ,子类
public class Student extends Person{
}
public class Application {
public static void main(String[] args) {
Student student=new Student();
student.say();
System.out.println(student.getMoney());
}
}
super
注意点:
1.super调用父类的构造方法,必须在构造方法的最前面
2.super只能出现在子类方法或构造方法中
3.super和this不能同时调用构造器
VS this:
代表的对象不同:
this:本身调用者这个对象
super:代表父类对象的应用
前提:
this:没有继承也可以使用
super:只能在继承条件下才可以使用、
构造方法:
this():本类的构造方法
super():父类的构造
public class Person {
public Person() {
System.out.println("Person无参被执行了");
}
protected String name="kuangshen";
public void print(){
System.out.println("Person");
}
//私有的不能被继承
public void print2(){
System.out.println("Person");
}
}
public class Student extends Person {
private String name = "qinjiang";
public Student() {
// 隐藏代码,调用父类无参super()
super();//显示调用父类构造器的话,必须放在子类构造器的第一行
System.out.println("Student无参被执行了");
}
public void print(){
System.out.println("student");
}
public void test1(String name) {
System.out.println(name);//秦疆
System.out.println(this.name);//qinjiang
System.out.println(super.name);//kuangshen
System.out.println("============");
print();//student
this.print();//student
super.print();//Person
}
}
import com.oop.Demo05.Student;
public class Application {
public static void main(String[] args) {
// Person无参被执行了
// Student无参被执行了
Student student=new Student();
// student.test("秦疆");
// student.test1("秦疆");
}
}
父类私有方法不能被继承,子类构造方法中都隐藏代码super()调用父类构造方法,若显示调用父类构造器的话,必须放在子类构造器的第一行;
this.方法()和方法()都是调用本类的方法
super.方法()是调用父类的