Sunday 22 May 2016

Abstract Class vs Interface in Java

This is very frequent question asked in Interview.Today we will try to understand the Abstract class and Interface in Java.

Abstract Class vs Interface in Java
Abstract Class:-


  • A class that is preceded with keyword “abstract” is known as abstract class.
  • It extended by other class and its method implemented.
  • It can’t be instantiated means we cant create the object of abstract class.
  • it may or may not include abstract methods.
  • An abstract method is a method that is declared without an implementation (without braces, and followed by a semicolon), as below,
          abstract returnType methodName(argument1 a, argument2 b);


  • If a class contain abstract methods, then the class itself must be declared abstract.
  • When an abstract class is subclassed, the subclass usually provides implementations for all of the abstract methods in its parent class. However, if it does not, then the subclass must also be declared abstract.
  • abstract class may contain non-final and final variables. 
     abstract classes can be use in below situation,
                1-If need to share code among closely related classes.
               2-classes that extend your abstract class have many common methods or fields,                       or require access modifiers other than public.
               3-declare non-static or non-final fields. It enables us to define methods that can                        access and modify the state of the object to which they belong. 

Interface :-
  • An interface is basically a contract -- it doesn't have any implementation. 
  • An interface can contain only method declaration; it cannot contain method definition.
  • In interface all fields are automatically public, static, and final and all methods (as default methods) are public.
  • The class that implements the interface should implement all the members of an interface. Like abstract classes, an interface cannot be instantiated.
  • interface is used to "implements“ whereas abstract class is used to "extends".
  • interface can be used to achieve multiple inheritance.

  • interface is more flexible than abstract class because one class can only "extends" one super class, but "implements" multiple interfaces.


  • interface can be use in below situation,
         1-we expect that unrelated classes will implement interface(the interfaces Comparable             and Cloneable are implemented by many unrelated classes)
           2-Need to specify the behaviour of a particular data type, but not concerned about who             implements its behaviour.
           3-Need to take advantage of multiple inheritance.

    No comments:

    Post a Comment

    Find Duplicate Characters In String using Java

    package com.zia.test; import java.util.HashMap; import java.util.Map; import java.util.Set; public class findDuplicateCharacter { /**...