继承及其在Java中的实现
Java继承
Java中的继承是一种允许类继承其他类的功能的方法。
也称为IS-A关系。
通过使用extends关键字,我们可以在java中实现继承。
继承的优点是代码的可重用性。
与继承相关的重要术语:
父类:
也称为超类或基类,父类的定义是其属性(或特征)被继承的类。
子类:
也称为子类或派生类,子类的定义是继承其他类的属性(或功能)的类。
如何在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
热门推荐
10 财运虎年祝福语简短语
11 单亲爸爸春节祝福语简短
12 狗狗上厕所训练
13 植物种植祝福语简短
14 翻译考试祝福语朋友简短
15 个人周年庆简短祝福语
16 狗狗怎么训练
17 分别祝福语简短搞笑英文
18 生日广州男生祝福语简短