Java 和多重继承
在 Java 中,我们使用继承来允许创建类的分层分类和对象。顾名思义,继承是类继承另一个类成员的能力。其属性被继承的类称为超类,而继承超类的类称为子类。我们使用 extends 关键字来继承类。Java 中有几种类型的继承,例如单继承和多级继承。在本文中,我们将专门探讨多重继承。
Java 中的多重继承
在面向对象编程的术语中,多重继承是指单个子类继承多个超类的能力。与其他面向对象编程语言不同,Java 不支持类的多重继承,而是允许接口的多重继承。
多重继承的可视化表示 -

为什么 Java 不支持类的多重继承?
一句话概括,这个问题的答案是为了防止歧义。在上图中,我们可以看到类 C 同时扩展了类 A 和类 B。假设这两个类都有相同的方法 display()。在这种情况下,Java 编译器将无法确定应该调用哪个 display 方法。因此,为了防止这种歧义,Java 限制了类的多重继承。此类歧义的一个示例是菱形问题。
示例
以下示例说明了如果尝试类的多重继承会发生什么结果。
class Event { // first superclass
public void start() {
System.out.println("Start Event");
}
}
class Sports { // 2nd superclass
public void play() {
System.out.println("Play Sports.");
}
}
// subclass extending both superclass
class Hockey extends Sports, Event {
public void show() {
System.out.println("Show Hockey.");
}
}
public class Tester{
public static void main(String[] args) {
// creating instance of subclass
Hockey hockey = new Hockey();
// calling the method of subclass
hockey.show();
}
}
输出
Tester.java:12: error: '{' expected
class Hockey extends Sports, Event {
^
1 error
错误显示,即使使用不同的方法,Java 中也不支持类的多重继承。
为什么 Java 支持接口的多重继承?
在 Java 中,接口有两个用途:纯抽象和多重继承。通常,接口由抽象方法和变量组成,这些方法和变量定义了类可以实现的行为。这里,抽象方法是没有实现或主体的方法,并且使用 abstract 关键字声明。
由于抽象方法的这一特性,Java 允许接口的多重继承。抽象方法不包含任何定义,如果我们想使用它,我们需要在子类中定义它。这样,该方法只有一个定义,我们可以轻松地实现多重继承。
要创建接口,我们使用关键字“interface”,要在类中访问其成员,我们需要在定义该类时使用“implements”关键字。
语法
interface nameOfInterface {
method1();
method2();
}
示例
以下示例说明了使用接口实现多重继承的实际应用。
interface Event { // interface 1
public void start();
}
interface Sports { // interface 2
public void play();
}
// another interface extending 1st and 2nd interface
interface Hockey extends Sports, Event{
public void show();
}
public class Tester{
public static void main(String[] args){
// creating instance of hockey
Hockey hockey = new Hockey() {
// implementing the methods of interfaces
public void start() {
System.out.println("Start Event");
}
public void play() {
System.out.println("Play Sports");
}
public void show() {
System.out.println("Show Hockey");
}
};
// calling the methods using instance
hockey.start();
hockey.play();
hockey.show();
}
}
输出
Start Event Play Sports Show Hockey
示例
在此示例中,我们将声明两个接口,它们具有相同名称但签名不同的方法,然后尝试实现多重继承。
interface Message1 { // interface 1
public void method();
}
interface Message2 { // interface 2
public void method(int id);
}
public class IntrfExample3 implements Message1, Message2 {
// using the method here with different definition
public void method() {
System.out.println("Tutorialspoint");
}
public void method(int id) {
System.out.println("ID: " + id);
}
public static void main(String []args){
// object creation
IntrfExample3 exp = new IntrfExample3();
// method calling
exp.method();
exp.method(125);
}
}
输出
Tutorialspoint ID: 125
结论
我们从定义继承开始本文,在下一节中,我们讨论了多重继承,这是一种继承类型,其中一个子类扩展了两个或多个超类的属性。一般来说,Java 不支持类的多重继承,但我们可以使用接口代替类来达到同样的目的。
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP