继承的概念
继承是java面向对象编程技术的一块基石,因为它允许创建分等级层次的类。
继承就是子类继承父类的特征和行为,使得子类对象(实例)具有父类的实例域和方法,或子类从父类继承方法,使得子类具有父类相同的行为。
类的继承格式
在 Java 中通过 extends 关键字可以申明一个类是从另外一个类继承而来的,一般形式如下:
class 父类 { }
class 子类 extends 父类 { }
继承案例:
父类
public class Person { //使用默认修饰符 String name; //无参构造方法 public Person() { System.out.println("execute Person( )"); } //有参构造方法 public Person(String name) { this.name = name; System.out.println("execute Person(name)"); } } 子类
public class Student extends Person { String school; public Student() { System.out.println("execute Student( )"); } public Student(String name, String school) { super(name); this.school = school; System.out.println("execute Person(name,school)"); } } 子类
public class PostGraduate extends Student{ String guide; public PostGraduate() { super(); System.out.println("execute PostGraduate( )"); } public PostGraduate(String name, String school, String guide) { super(name, school); this.guide = guide; System.out.println("execute Person(name,school,guide)"); } }
通过继承,子类继承了父类的属性,并且自己也拥有自己独特的属性