📜  Java继承和接口之间的区别

📅  最后修改于: 2021-07-05 07:33:29             🧑  作者: Mango

Java是最流行和广泛使用的编程语言之一。多年来, Java一直是最受欢迎的编程语言之一。 Java是面向对象的。但是,它不被视为纯粹的面向对象的,因为它提供了对原始数据类型(如int,char等)的支持。在本文中,我们将了解Java两个最重要的概念,继承和接口之间的区别。

接口:接口是类的蓝图。它们指定类必须执行的操作,而不是指定如何执行的操作。像类一样,接口可以具有方法和变量,但是默认情况下,在接口中声明的方法是抽象的(即),它们仅包含方法签名,而不包含方法的主体。接口用于实现完整的抽象。

继承:这是Java的一种机制,通过该机制,一个类可以继承另一类的功能。 Java可能有多个继承。他们是:

  1. 单一继承:在单一继承中,子类继承一个超类的功能。在下图中,类A用作派生类B的基类。

  2. 多级继承:在多级继承中,派生类将继承基类,并且派生类也充当其他类的基类。在下图中,类A充当派生类B的基类,后者又充当派生类C的基类。在Java,类无法直接访问祖父母的成员。

    多级继承1

  3. 层次继承:在层次继承中,一个类充当多个子类的超类(基类)。在下图中,类A用作派生类B,C和D的基类。

    层次继承1

下表描述了继承和接口之间的区别:

Category Inheritance Interface
Description Inheritance is the mechanism in java by which one class is allowed to inherit the features of another class. Interface is the blueprint of the class. It specifies what a class must do and not how. Like a class, an interface can have methods and variables, but the methods declared in an interface are by default abstract (only method signature, no body).
Use It is used to get the features of another class. It is used to provide total abstraction.
Syntax class subclass_name extends superclass_name {
}
interface {
}
Number of Inheritance It is used to provide 4 types of inheritance. (multi-level, simple, hybrid and hierarchical inheritance) It is used to provide 1 types of inheritance (multiple).
Keywords It uses extends keyword. It uses implements keyword.
Inheritance We can inherit lesser classes than Interface if we use Inheritance. We can inherit enormously more classes than Inheritance, if we use Interface.
Method Definition Methods can be defined inside the class in case of Inheritance. Methods cannot be defined inside the class in case of Interface (except by using static and default keywords).
Overloading It overloads the system if we try to extend a lot of classes. System is not overloaded, no matter how many classes we implement.
Functionality Provided It does not provide the functionality of loose coupling It provides the functionality of loose coupling.
Multiple Inheritance We cannot do multiple inheritance (causes compile time error). We can do multiple inheritance using interfaces.