Interface and Abstract Classes

Interface and Abstract Classes

 Interfaces:

Class - Blue print of an entity.
Class consist of :
  • Methods(Behaviour)
  • Attributes(entities/elements/variables)

Defining a method means - Just providing method signature.
<access_modifier> <return_datatype> <method_name>(<list of parameters with it's respective datatype);

In this case you are not going to have any body of the method.
Interface can have more than one methods definitions(abstract methods).


Interfaces are blue print of behaviours(methods). It means set of methods which can be used for classification. It will help corporate to enforce template for coding to their developers.


implements keyword will force your class to implement the methods which interface in it else your class will become an abstract class and then you need to extend that class with other one to implement the missed method to make your ultimate inheriting child class a runnable class(absolute class).

Purpose of inheritance is code reusability as you can override or can overload any method in child class.
Purpose of interface is to classify your class or your code to do some similar behaviour type of task.


list<Animal> list = new ArrayList();
list.add(new cat());
Animal is inteface and cat is a class which is implementing interface Animal.


You cannot create an object of any interface as object can be created of only an absolute class.
As object need to know about it's method implementation code and if you are having an abstract method then you can't create an object of such interface or abstract class.

Benefit of interface:
You can enforce developer to use all the methods defined in it. Implementer will not be able to modify the method name and it's return type in-short method definition will be same.


For sample:

Implementation of stack in Java as stack can be implemented by using ArrayList or by using LinkedList.

It is classic example of interface. As here you can create an object as 
Stack s = new ArrayList();
Stack s1 = new LinkedList();



If animal is an interface then you can't create it's object.
Animal a = new Animal(); -> not allowed.

Interface example with stack implementation as it is collection element in Java and can be implement by using array/linkedlist and other datastructures.






Comments

Popular posts from this blog

Inheritance and Polymorphism

OOPS concept 1

OOPS 2 - Encapsulation (access modifiers and constructors)