Java是最流行和最广泛使用的编程语言之一。多年来, Java一直是最流行的编程语言之一。 Java是面向对象的。但是,它不被视为纯粹的面向对象,因为它提供对原始数据类型(如 int、char 等)的支持。在本文中,我们将了解Java两个最重要的概念,继承和接口之间的区别。
接口:接口是类的蓝图。它们指定了一个类必须做什么而不是如何做。和类一样,接口可以有方法和变量,但是接口中声明的方法默认是抽象的(即它们只包含方法签名而不包含方法体)。接口用于实现完整的抽象。
继承: Java的一种机制,允许一个类继承另一个类的特性。 Java可能存在多重继承。他们是:
- 单继承:在单继承中,子类继承一个超类的特性。在下图中,类 A 作为派生类 B 的基类。
- 多级继承:在多级继承中,派生类将继承基类,并且派生类也充当其他类的基类。在下图中,类 A 作为派生类 B 的基类,而派生类 B 又作为派生类 C 的基类。在Java,类不能直接访问祖父母的成员。
- 分层继承:在分层继承中,一个类充当多个子类的超类(基类)。在下图中,类 A 作为派生类 B、C 和 D 的基类。
下表描述了继承和接口的区别:
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. |