类扩展多个类Java? [英] Class extending more than one class Java?

查看:140
本文介绍了类扩展多个类Java?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道一个类可以实现多个接口,但是可以扩展多个类吗?例如,我想我的类扩展 TransformGroup 和我创建的类。这是可能在Java吗?两个语句类X扩展TransformGroup扩展Y 类X扩展TransformGroup,Y 接收错误。如果不可能,为什么? TransformGroup extends Group 但我想它也扩展 Node 它从 Node 继承字段,并且它可以在需要 Node 对象的地方传递。此外,像Java中的所有类一样,它们扩展 Object 类。那么为什么不可能扩展到多个类呢?



TransformGroup继承



因此,如果可能,什么是正确的方法呢?如果不是,我为什么和如何解决这个问题?

解决方案

在Java中不允许多重继承。



场景1:如您所知,以下是不可能的in Java:

  public class Dog extends Animal,Canine {

}



情况2:但以下是可能的:

  public class Canine extends Animal {

}

public class Dog extends Canine {

}

这两种方法的区别是在第二种方法中有一个明确定义的父或 super 类,而在第一种方法中, super 类是不明确的。



考虑 Animal Canine drink()。在第一种情况下,如果我们调用 Dog.drink(),将调用父方法?在第二种情况下,我们知道调用 Dog.drink()会调用 Canine classes 饮料方法,只要 Dog 没有覆盖它。


I know that a class can implement more than one interface, but is it possible to extend more than one class? For example I want my class to extend both TransformGroup and a class I created. Is this possible in Java? Both statements class X extends TransformGroup extends Y and class X extends TransformGroup, Y receive an error. And if it is not possible, why? TransformGroup extends Group but I guess it also extends Node since it inherits fields from Node and it can be passed where a Node object is required. Also, like all classes in Java, they extend Object class. So why wouldn't it be possible to extend with more than one class?

TransformGroup inheritance

So, if that is possible, what is the proper way to do it? And if not, why and how should I solve the problem?

解决方案

In Java multiple inheritance is not permitted. It was excluded from the language as a design decision, primarily to avoid circular dependencies.

Scenario1: As you have learned the following is not possible in Java:

public class Dog extends Animal, Canine{

}

Scenario 2: However the following is possible:

public class Canine extends Animal{

}

public class Dog extends Canine{

}

The difference in these two approaches is that in the second approach there is a clearly defined parent or super class, while in the first approach the super class is ambiguous.

Consider if both Animal and Canine had a method drink(). Under the first scenario which parent method would be called if we called Dog.drink()? Under the second scenario, we know calling Dog.drink() would call the Canine classes drink method as long as Dog had not overridden it.

这篇关于类扩展多个类Java?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆