Java中的继承是一种允许类继承其他类的功能的方法。
也称为IS-A关系。
通过使用extends关键字,我们可以在java中实现继承。
继承的优点是代码的可重用性。
与继承相关的重要术语:
父类:
也称为超类或基类,父类的定义是其属性(或特征)被继承的类。
子类:
也称为子类或派生类,子类的定义是继承其他类的属性(或功能)的类。
我们借助extends关键字实现继承。
语法:
class Parent { public void method1() { //字段和声明 } } class Child extends Parent { public void method2() { //字段和声明 } }
示例
在下面的继承示例中,Parent类是父类,Child类是扩展Parent类的子类。
/*Java program to demonstrate the concept of inheritance */ //家长班 class Parent { //Parent类有一种方法 // displayParentMessage()打印父类消息的方法 public void displayParentMessage() { System.out.println("Hello, we are in parent class method"); } } //子类或派生类 class Child extends Parent { //Child子类添加了另一种方法 // displayChildMessage()打印父类消息的方法 public void displayChildMessage() { System.out.println("Hello, we are in child class method"); } } //我们将在该类的主类中创建 //父子类的对象 class Main { public static void main(String[] args) { //创建父类对象 Parent p = new Parent(); //通过父类对象调用父类方法 p.displayParentMessage(); //创建Child类对象 Child c = new Child(); //通过子类对象调用子类方法 c.displayChildMessage(); //通过子类对象调用父类方法 c.displayParentMessage(); } }
输出结果
D:\Programs>javac Main.java D:\Programs>java Main Hello, we are in parent class method Hello, we are in child class method Hello, we are in parent class method