What is the Difference Between Inheritance and Interface in Java?

🆚 Go to Comparative Table 🆚

Inheritance and interface are two distinct concepts in Java that serve different purposes. Here are the key differences between them:

Inheritance:

  • Inheritance is a mechanism in Java that allows one class to inherit features from another class.
  • It is used to create a hierarchy between multiple classes by replicating some of the methods and properties from a base class to its child class.
  • Inheritance promotes code reusability, as the child class can reuse the code from the parent class using the override method.
  • There are various types of inheritance in Java, such as single inheritance, multiple inheritance, multilevel inheritance, hybrid inheritance, and hierarchical inheritance.
  • Inheritance is primarily used when you want to share functionality between classes.

Interface:

  • An interface is a blueprint of a class, specifying what a class must do without specifying how it should be done.
  • Interfaces can contain abstract methods ( studi 2021-12-03 21:35:08)

Comparative Table: Inheritance vs Interface in Java

Here is a table comparing the differences between inheritance and interfaces in Java:

Feature Inheritance Interface
Description Inheritance allows one class to inherit properties and methods of another class. An interface is a blueprint of a class, specifying what a class must do without defining how.
Definition There can be only one base class and one derived class in both single and multiple inheritance in Java. An interface can extend another interface, allowing multiple inheritance.
Abstraction Inheritance provides code reusability. Interfaces provide abstraction and multiple inheritance.
Methods Inheritance allows a class to inherit the methods of its superclass. Methods declared in an interface are by default abstract, with only the method signature and no body.
Accessibility Inheritance allows a subclass to access public and protected members of its superclass. An interface can have public, protected, and private variables, but all methods are public by default.

In summary, inheritance in Java is used to create a hierarchy between multiple classes by replicating some properties from others, while interfaces provide a mechanism for implementing abstraction and multiple inheritance. Inheritance allows one class to inherit properties and methods from another class, and interfaces allow multiple classes to share a common set of properties and methods without defining their implementation.