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

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

问题描述

我们可以通过使用抽象类来实现与接口相同的功能,那么为什么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天全站免登陆