由于Java中的一个类不能扩展多个类.我将如何获得这个呢? [英] Since a class in Java cannot extend multiple classes. How would I be able to get by this?

查看:74
本文介绍了由于Java中的一个类不能扩展多个类.我将如何获得这个呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个需要扩展一个类的类.我遇到了编译器错误,因为这在Java中无法发生.我知道您可以在Java中实现想要的尽可能多的接口,但只能扩展另一个类.我该如何解决这个问题?

I have two classes that need to extend one class. I am getting a compiler error since this cannot happen in Java. I know that you can implement as many interfaces you want to in Java but can only extend one other class. How can I fix this problem?

推荐答案

使用具有A"关系而不是是".

Use a "has A" relationship instead of "is An".

class A
class B

您(想)自己想要的:

class C extends A, B

相反,请执行以下操作:

Instead, do this:

class C {
  A theA;
  B theB;
}

几乎总是滥用多重继承.扩展类作为导入其数据和方法的简便方法是不合适的.如果您扩展一个类,则它实际上应该是是一个"关系.

Multiple inheritance is almost always abused. It's not proper to extend classes just as an easy way to import their data and methods. If you extend a class, it should truly be an "is An" relationship.

例如,假设您有课程,

class Bank extends Financial
class Calculator

如果要使用 Bank 中的 Calculator 的功能,则可以执行此操作,

You might do this if you want to use the functions of the Calculator in Bank,

class Bank extends Calculator, Financial

但是, Bank 绝对不是 Calculator .银行使用一个计算器,但它本身不是一个.当然,在Java中,您还是无法做到这一点,但是可以使用其他语言.

However, a Bank is most definitely NOT a Calculator. A Bank uses a Calculator, but it isn't one itself. Of course, in java, you cannot do that anyway, but there are other languages where you can.

如果您不购买其中的任何一个,并且您真的希望 Calculator 的功能成为 Bank 界面的一部分,则可以通过以下方式实现Java接口.

If you don't buy any of that, and if you REALLY wanted the functions of Calculator to be part of Bank's interface, you can do that through Java interfaces.

interface CalculatorIntf {
  int add(int a, int b);
}

class Calculator implements CalculatorInf {
  int add(int a, int b) { return a + b };
}

class Bank extends Financial implements CalculatorIntf
  Calculator c = new Calculator();

  @Override // Method from Calculator interface
  int add(int a, int b) { c.add(a, b); }
}

一个类可以实现任意数量的接口.请注意,从技术上讲,这仍然是具有A"关系

A class can implement as many interfaces as it wants. Note that this is still technically a "has A" relationship

这篇关于由于Java中的一个类不能扩展多个类.我将如何获得这个呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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