gpt4 book ai didi

java - 这是java中的多重继承吗?为什么Java不支持extends ChildOne,ChildTwo语法?

转载 作者:行者123 更新时间:2023-11-30 03:20:55 25 4
gpt4 key购买 nike

我有三门课

子二

public class ChildTwo {
public void methodOfChildTwo() {
System.out.println("methodOfChildTwo.");
}
}

ChildOne 扩展了 ChildTwo

public class ChildOne extends ChildTwo{
public void methodOfChildOne() {
System.out.println("methodOfChildOne.");
}
}

扩展 ChildOne 的父级

public class Parent extends ChildOne{
public void methodOfParent() {
System.out.println("methodOfParent.");
}
}

当我创建Parent对象时,我可以调用所有三个方法,因为所有这些方法都是在Parent类中继承的。

Parent parent =new Parent();
parent.methodOfParent();
parent.methodOfChildOne();
parent.methodOfChildTwo();

我的问题是

  1. 我这样说可以在Java中实现多重继承吗?
  2. 这种方法概念上与多个扩展类似,例如Parent extends ChildOne,ChildTwo (Java 不支持这些语法)。尽管我们可以通过上述方式实现这一点,但为什么Java不支持这种语法?

请有人澄清。

最佳答案

首先Java不支持多重继承,因为它可能会导致歧义。 (注意:像 C++ 这样的语言确实支持多重继承)。

1.Can I say this way I can achieve multiple inheritance in Java?

这仍然不是多重继承。

请参阅下面的图表:

enter image description here

您给定的代码就像右侧的图表。多重继承将直接从其所有父级继承所有属性和行为(Java 中不支持)。

2.This approach is conceptually similar with multiple extends, like Parent extends ChildOne,ChildTwo (Java does not supports these syntax).

您的方法实际上在概念上与多重扩展并不相似。 Java 不支持这一点以防止歧义。想象一下两个父类都有一个类似签名的方法。

class Bomb{
public void activate();
}

class LightBulb{
public void activate();
}

class Child extends Bomb, LightBulb{ //Imagine if this is allowed
//When I call activate(), will it activate the bomb or the lightBulb?
}

Why Java does not supports this syntax, although we can achieve this in above mentioned way?

两种情况不同,无法通过a extends bb extends c实现多重继承。从概念上讲,它是不同的,因为层次结构完全不同。

在多重继承中,您想要扩展的两个父类可以完全不相关。想象一下Pegasus 扩展了 FlyingCreature、Horse

Pegasus 一个FlyingCreature,它也是也是一个,但是FlyingCreatureHorse 根本不相关

在您给定的示例中,所有后续扩展父类都是另一个父类的子集。它们都是相关的。

哺乳动物 动物狮子 哺乳动物is 也是 Animal。

<小时/>

如果您说您提到的方法在概念上类似于多重继承,请考虑以下场景:

您的任务是从 FlyingCreature 类Horse 类 创建 Pegasus 类

你打算这样做吗?

class FlyingCreature{
}

class Horse extends FlyingCreature{ //But Horses do not fly!
}

class Pegasus extends Horse{ //You got what you want here, but the Horse class is wrong.
}

还是这个?

class Horse{
}

class FlyingCreature extends Horse{ //All flying creatures are horses? Are you sure?
}

//You got what you want here, but the FlyingCreature class is wrong.
class Pegasus extends FlyingCreature {
}

所以现在你看,这是不可能完成的,因为两个父类根本不相关。为了在某​​种程度上实现所谓的“多重继承”,Java 使用接口(interface)

关于java - 这是java中的多重继承吗?为什么Java不支持extends ChildOne,ChildTwo语法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31349072/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com