Saturday, August 19, 2017

Abstract and Interface

Abstract 

A class that is declared with abstract keyword, is known as abstract class in java. It can have abstract and non-abstract methods (method with body).
Abstraction is a process of hiding the implementation details and showing only functionality to the user.
A class that is declared as abstract is known as abstract class. It needs to be extended and its method implemented. It cannot be instantiated.
abstract class

abstract class A{} 
abstract method

A method that is declared as abstract and does not have implementation is known as abstract method.
Example abstract method

abstract void printStatus();//no body and abstract 
An interface in java is a blueprint of a class. It has static constants and abstract methods.


Interface 

The interface in java is a mechanism to achieve abstraction. There can be only abstract methods in the java interface not method body. It is used to achieve abstraction and multiple inheritance in Java.

Java Interface also represents IS-A relationship.

It cannot be instantiated just like abstract class.

Why use Java interface?

There are mainly three reasons to use interface. They are given below.

It is used to achieve abstraction.
By interface, we can support the functionality of multiple inheritance.
It can be used to achieve loose coupling.


Why multiple inheritance is not supported in java?

To reduce the complexity and simplify the language, multiple inheritance is not supported in java.

Consider a scenario where A, B and C are three classes. The C class inherits A and B classes. If A and B classes have same method and you call it from child class object, there will be ambiguity to call method of A or B class.


Since compile time errors are better than runtime errors, java renders compile time error if you inherit 2 classes. So whether you have same method or different, there will be compile time error now.

No comments:

Post a Comment