抽象类和多重继承 [英] Abstract classes and Multiple Inheritance

查看:28
本文介绍了抽象类和多重继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们可以通过抽象类来实现和接口一样的功能,那么为什么java不允许下面的代码呢?

We can achieve the same functionality as interfaces by using abstract classes, So why java doesn't allow the following code?

abstract class Animals
{
    public abstract void run();
}

abstract class Animals1
{
    public abstract void run1();
}

class Dog extends Animals,Animals1
{
  public void run() {System.out.println("Run method");}
  public void run1() {System.out.println("Run1 method");}
}

我知道只使用接口可以实现多重继承,但上面的代码和接口做的事情是一样的.

I know that multiple inheritance can be achieved by using only interfaces but the above code does the same thing as the interfaces would have done it.

推荐答案

这是不允许的,因为您可以使用抽象类做更多的事情.允许多重继承是没有意义的,前提是您只在可以使用接口时才使用抽象类.

This is not allowed because you can do more than this with abstract classes. It wouldn't make sense to allow multiple inheritance, provided you only used an abstract class when you could have used an interface.

对于不能用接口做的事情,只使用抽象类更简单,在这种情况下,你将无法使用两个抽象父类.

It is simpler to only use abstract classes for things you can't do with an interface, in which case you wouldn't be able to use two abstract parent classes.

注意:在 Java 8 中,你不能用接口做的事情少了,你可以有公共实例和静态方法和实现.

Note: with Java 8 there is less you can't do with an interface, you can have public instance and static methods with implementations.

在 Java 9 中,您将能够在接口中使用 private 方法;)

In Java 9 you will be able to have private methods in interfaces ;)

这篇关于抽象类和多重继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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