类扩展 java,类扩展多个类Java?

本文探讨了Java中是否允许一个类同时继承多个类,并通过实例解释了为何不允许。作者揭示了Java设计决策背后的原因,讨论了替代方案,如明确超类和使用组合。最后,提供了关于如何在Java中处理此类问题的建议。
摘要由CSDN通过智能技术生成

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?

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值