Showing posts with label abstraction. Show all posts
Showing posts with label abstraction. Show all posts

Difference between Interfaces and Abstract Classes

What is the differences between interface and abstract classes?

This is one of the most widely asked question in an interview at any level. In this post we are going to focus on differences between interface and abstract classes, what are ideal situations in development for using these etc. 

While designing a software or an API we don’t want Base class to be instantiated directly, we just want the base class to provide a structure that needs to be implemented by sub classes. This can be achieved using abstract classes. Interface takes this concept one step further by preventing any method or function implementation at all. 

Differences between interfaces and abstract classes :

1. Prior to Java 8 interfaces can only have abstract methods without any implementation but java 8 on wards we can now have default implementation of methods in interfaces and for that we can use default keyword at the beginning of method signature. Abstract classes can have abstract as well as non abstract methods.

2. Variables declared in interfaces are final by default whereas abstract classes can have non-final variables as well. 

3. Abstract classes can extend interfaces but reverse is not possible.

4. In java we implements interfaces using implements keyword whereas we extend abstract classes by using extends keyword.

5. We can implement more than one interface but we can not extend more than one abstract class.

6. Members of interface in java are public by default, members of abstract classes can have any access specifier.

Diamond problem and use of interface. 

Consider a secenario where we are designing an API for drawing different shapes. First let’s design this using abstract classes. We have created a parent class Shape with all necessary functions that needs to be implemented by it’s sub classes. Now let's create two sub classes one is Circle and other is Square and both extends Shape class. Now what if we want to create a new shape Circle on Square we can’t reuse Circle and Square classes here because only one class can be extended. 
This is know as diamond problem, we can use interfaces to resolve this type of design problems. 

When to use abstract class?

In  case  where  we want  to  use  implementation inheritance  then it  is usually provided by  an  abstract  base class.  Abstract  classes are  excellent  candidates inside of  application frameworks.  Abstract  classes  let  us define  some default  behavior and force subclasses to  provide any  specific behavior.  Care  should be taken not  to  overuse implementation inheritance.

When to use interface?

For polymorphic interface inheritance,  where the client  wants to  only  deal  with  a type  and  does  not  care  about  the  actual  implementation  use  interfaces.  If  you  need  to  change  your design frequently,  you  should  prefer  using interface to  abstract.  Coding  to  an interface inheritance can achieve  code  reuse  with  the help of  object  composition.  For example:  The Spring  reduces coupling  and framework’s  dependency  injection promotes  code to  an  interface principle.  Another justification for using  interfaces is that  they  solve the  ‘diamond problem’ of  traditional  multiple  inheritance as  discussed above. Java  does  not support  multiple  inheritance.  Java only supports  multiple interface inheritance. Interface  will solve  all the ambiguities caused by  this ‘diamond  problem’. 

What is marker interface?

The interfaces  with  no  defined  methods  act  like markers.  They  just  tell  the  compiler that  the  objects  of  the classes implementing  the interfaces with  no defined  methods need  to  be  treated  differently.  Example  java.io.Serializable,  java.lang.Cloneable,  java.util.EventListener  etc.  Marker interfaces are also  known  as “tag” interfaces  since they  tag  all the derived  classes into  a category based on their purpose.
Share:

OOPs Concept - 4


What is abstraction?

Abstraction is one of the important concept in OOPs. Abstraction, basically means hiding unnecessary details and showing relevant information to users. Take for example, when we learn to drive a car we do not care about how it engines work, we only cares about how it's steering, brake and accelerator will work. We never get into the complication of car's internal working.

In OOPs abstraction is a process of hiding the implementation details from the user, only the functionality will be provided to the user. In other words, the user will have the information on what the object does instead of how it does it.

There are basically two types of abstraction :

Data Abstraction : Data abstraction is the way to create complex data types and exposing only meaningful operations to interact with data type, whereas hiding all the implementation details from outside work.
Advantage of this abstraction is that even if our internal implementation got change there will be no impact on client facing code since they only work with the exposed behavior not the internal implementation.

Control Abstraction : When we works on a application software, we sometimes write repetitive code at multiple places. Control abstraction is the process of identifying such statements and expose them as single unit of work. We normally use this feature when we create a function to perform any work.

How we achieve abstraction is Java?
In java abstraction is achieved by interfaces and abstract classes. Interfaces allows you to abstract implementation completely whereas abstract classes allows for partial abstraction.

Let's see an example for both of these:

Abstraction using interfaces

interface Animal{
     public void voice();
     public void eat();
}

class Dog implements Animal{
 
     @Override
     public void voice(){
          System.out.println("Dog Barks");
     }   

     @Override
     public void eat(){
          System.out.println("Dog eats Meat");
     }
}

class Cat implements Animal{
 
     @Override
     public void voice(){
          System.out.println("Cat Meows");
     }   

     @Override
     public void eat(){
          System.out.println("Cat drink Milk");
     }
}

class MainClass{
     public static void main(String[] args){
           Animal  dog = new Dog();
           dog.voice();
           dog.eat();
         
           Animal  cat = new Cat();
           cat.voice();
           cat.eat();
     }         
}


Remember we can not instantiate objects of interfaces directly. When we execute above main class we will get below output on console.

Dog Barks
Dog eats Meat
Cat Meows
Cat drink Milk


For abstract class example let's repeat our Employee example from previous post.

abstract class Employee{
 
        private String empName;
        private String empId;
     
        public void storeDetail(){
             System.out.println("Storing employee details");
        }

        public void showDetail(){
             System.out.println("Showing employee details");
        }

        public abstract void calculateSalary();
}

class PartTimeEmployee extends Employee{

        @Override
        public void calculateSalary(){
             System.out.println("Calculating salary for part time employee.");
        }
}


You might like to see : Difference between abstraction and interface.

This is all about abstraction is java, we will discuss about Encapsulation in next post. 
Share:

Popular Posts

Recent Posts

Followers

Total Pageviews