何为类的继承?
就是类之间的特性,父类(parent class)【或者称为超类(super class)】的行为和状态可以由它的子类(sub class)【或者派生类(derived class)】来继承,这样就可以减少重复的代码。
在Java中,实现类的继承,要使用extends关键字,格式如下:
[public ]class SubClass extends SuperClass{
//类体定义
}
注意一下,直接通过extends 相连的sub class 为 相对应的 super class 的直接子类,不然就为间接子类
先看一个代码:
package demo;
public class PersonSalary extends Person01{
public static void main(String[] args) {
new PersonSalary(10,"Lily");
}
public PersonSalary(int age,String name) {
super(20,name);
System.out.println("This is the PersonSalary ");
System.out.println(name + "'s age is " + age);
}
}
class Person01 extends Person02{
public Person01(int age,String name) {
super(30,name);
System.out.println("This is the Person");
System.out.println(name + "'s age is " + age);
}
}
class Person02{
public Person02(int age ,String name ) {
System.out.println("This is the Person");
System.out.println(name + "'s age is " + age);
}
}
先解释其中的super 的用法,就是调用父类的构造方法,当我们没有使用super 时,系统就会默认调用父类的默认构造方法
就是说,每次的时候,都会先调用父类的构造方法,再执行子类的类体,当这样的一个链状的结构形成时,我们可以说形成了链式继承结构
好啦,咱们看看代码运行结果:
子类可以调用父类的方法,成员变量
再看一个代码:
package demo;
public class PersonSalary extends Person01{
public static void main(String[] args) {
PersonSalary per =new PersonSalary(10,"Lily",2000);
per.print();
}
public PersonSalary(int age,String name) {
super(20,name);
System.out.println("This is the PersonSalary ");
System.out.println(name + "'s age is " + age);
}
public PersonSalary(int age,String name ,int salary) {
super(age,name);
this.salary = salary ;
}
}
class Person01 {
int age;
String name ;
int salary;
public Person01(int age,String name,int salary) {
this.age =age ;
this.name =name ;
this.salary = salary ;
}
public Person01(int age,String name) {
this.age = age ;
this.name =name ;
System.out.println("This is the Person");
System.out.println(name + "'s age is " + age);
}
public void print () {
System.out.println(name + "'s name and his age is " + age +" the salary is " + salary );
}
}
想一想输出结果:
好啦,就介绍这么多啦!