Thursday, 7 September 2017

When to use Abstract class and When to use Interface in Java


  • Abstraction is one among the oops concepts and it means hiding the implementation details.In java abstraction can be achieved by two methods.
    1. Abstract Class
    2. Interface
      Abstract Class
  • Abstract class contains both unimplemented and implemented methods. Abstratct class must have the keyword abstract and it may not contains any abstract method.
  • If it acontains any abstract method then all subclasses must have to implement it.
  • Abstarct classes can be initiated by exending it.
  • We can use abstract class when some functionalities are common across all subclasses and some of the functionlaties differs.
  • Consider we have Bank as abstarct class and it has implemented methods deposit() and withdraw(). Here deposit() and withdraw() are common across all banks. calcualte() is varies based on bank differs. So here we can use abstarct class.
      Bank.java
public abstract class Bank { public void deposit(double ammount) { System.out.println("Ammount has deposited, " + ammount); } public void withdraw(double ammount) { System.out.println("Ammount has withdrawn, " + ammount); } public abstract double calculateInterest(); }
      HDFC.java
public class HDFC extends Bank { private static final double MONTHLY_DEDUCTION = 12; private static final double YEARLY_DEDUCTION = 40; private double ammount = 1000; @Override public double calculateInterest() { double interest = ammount + MONTHLY_DEDUCTION + YEARLY_DEDUCTION; return interest; } }
      ICICI.java
public class ICICI extends Bank { private static final double MONTHLY_DEDUCTION = 12; private static final double QUARTARLY_DEDUCTION = 15; private double ammount = 1000; @Override public double calculateInterest() { double interest = ammount + MONTHLY_DEDUCTION + (QUARTARLY_DEDUCTION * 4); return interest; } }
      Interface
  • Interface is a blueprint of a class and it contains only public abstract methods and staic final variables(contants)
  • Sub classes able implemeting interface by implementing all nethods.
  • Interfaces can be use when we need to achieve muliple inheritance because it supports multiple inheritance.
Java 8
  • After being introduced Default Method, the Interfaces and abstract Classes seems similar, however, they still different concept in Java 8.
  •  Abstract Class can define constructor. They are more structured and can have a state associated with them. 
  • While in contrast, default method can be implemented only in the terms of invoking other Interface methods, with no reference to a particular implementation's state. Hence, both use for different purposes and choosing between two really depends on the scenario context.

No comments:

Post a Comment

Search This Blog

Contact us

Name

Email *

Message *