Difference between Abstract Class vs Interface Java Example

In this post let’s discuss about Abstract class v/s interface in java along with an example. Abstract Class and Interface are core part of java programming language and its a frequently asked java interview question.

basic meaning

 

Above diagram illustrate the basic meaning of Abstract class v/s interface in java, let’s understand technical differences one by one with an example.

Introduction

Java Abstract class and Interface is mainly used with abstraction in java.

An abstraction in java is a method of hiding the internal implementation and showing only the functionality to the users, i.e. showing what way it works and hiding how it will works.

Difference No.1

  • An abstract class at a time it can extend only one Java class or abstract class and implement multiple Java interfaces.
Example

Example 1.a

  • An interface can extend any number of interfaces at a time.
Example

example1.b

Difference No.2

  • Abstract class can be extended (inherited) by a class or an abstract class.
Example

example2a

  • An interface can only extend another interface.
Example

example2b

Difference No.3

  • An abstract class can have both abstract and concrete methods.
Example

example3a

  • An interface can have only abstract methods.
Example

example3b

Difference No.4

  • In abstract class keyword called “abstract” is mandatory to declare a method as an abstract.
Example

example4a

  • In an interface keyword called “abstract” is optional to declare a method as an abstract.
Example

example4b

Difference No.5

  • An abstract class can have protected and public abstract methods.
Example

example5a

 

  • An interface can have only public abstract methods.
Example

example5b

Difference No.6

  • An Abstract class can have final, non-final, static and non-static variables with any access specifier.
Example

example6a

  • Interface can only have public static final (constant) variable.
Example

example6b

Difference No.7

  • An Abstract class does not support multiple inheritance.
  • Interface supports multiple inheritance.

Difference No.8

  • Abstract class can support the implementation of interface.
  • Interface cannot support the implementation of abstract class.

Use cases

Abstract Class in Java

  • Abstract in java classes need to share few codes then we can use these classes in abstract classes.
  • It is used to define a state of an object i.e we need to define a non-static or non-final fields.

Interface in Java

  • It is used when there is a total abstraction.
  • It is also used in multiple inheritances.

“In this post successfully we understood the basic meaning, differences and use cases of Abstract class v/s interface in java

 

Leave a Reply

Your email address will not be published. Required fields are marked *