Friday, March 20, 2020

Abstract Class vs Interface

Abstract Class, Interface, Oracle Java Tutorial and Material, Oracle Java Exam Prep

In Java, the Abstract classes and interfaces are fundamental building blocks as they both are used to implement one of the essential concepts of Object-Oriented Programming that is, Abstraction. Though both of them are used for Abstraction, they differ from each other, and we cannot use them interchangeably. We will compare abstract class vs interface, along with real-life examples. We will also discuss when we should use interfaces and abstract classes.

Abstract Class In Java


An Abstract class is a class whose objects can’t be created. It is a kind of guideline or a template for other classes. An abstract class should contain at least one abstract method (method without any implementation or method body).

◉ The abstract class is declared with the help of an abstract keyword.

◉ An abstract class can be considered as an incomplete class that does not represent complete behavior.

◉ The abstract class can have abstract methods (methods without body) as well as concrete methods (methods with the body).

◉ We can not create objects or instances from the abstract classes, but they can be subclassed.

Syntax of writing Abstract classes:

abstract class TestAbstractClass
{
  public abstract void abstractMethod();
  public void normalMethod()
  {
    //method body
  }
}

Reasons For Using Abstract Class in Java


◉ An abstract class provides a guideline or template for other future specific classes.
◉ An Abstract class gives a default functionality of Inheritance.
◉ The abstract class helps in achieving code reusability.
◉ The abstract class also allows us to define a common interface for its subclasses.

Abstract Methods in Java


◉ Abstract methods are methods with no implementation. They do not contain any method statement.

◉ The child classes of this abstract class must provide the implementation of these inherited abstract methods.

◉ An abstract method is declared with an abstract keyword.

◉ The declaration of an abstract method must end with a semicolon ;

Syntax of declaring abstract methods:

access-specifier abstract return-type method-name();

Example of Abstract class:

package com.oraclejavacertified.abstractclass;
//parent class
abstract class Animal
{
  //concrete method
  public void show1()
  {
    System.out.println("Concrete method of parent class Class");
  }
  //abstract method
  abstract public void show2();
  }
//child class
Class Dog extends Animal
{
  // Must Override this method while extending the parent class
  public void show2()
  {
    System.out.println("Overriding abstract method of parent class");
  }
  //Overriding concrete method is not compulsory
  public void show1()
  {
    System.out.println("Overriding concrete method of parent class");
  }
}
public class AbstractClassDemo
{
  public static void main(String[] args)
  {
    Dog obj = new Animal();
    obj.show2();
    obj.show1();
  }
}

Output:

Overriding abstract method of parent class
Overriding concrete method of parent class

Rules to be followed for Abstract Class


◉ The abstract class cannot be instantiated or we can’t create objects from abstract classes.

◉ The child class which extends the abstract class should implement all the abstract methods of the parent class otherwise, the child class should also be declared as an abstract class.


Interfaces in Java


An interface is another building block of Java which is a blueprint or template of a class. It is much similar to the Java class but the only difference is that it has abstract methods and static constants. There can be only abstract methods in an interface, that is there is no method body inside these abstract methods. The class that implements the interface should be declared as abstract, otherwise, all the methods of the interface need to be defined in the class.

Syntax of declaring Interfaces in Java:

To declare an interface, the interface keyword is used. Here is a syntax to declare an interface:

interface interface-name
{
  //abstract methods
}

Example:

Following is an example of an interface:

//Filename: NameOfInterface.java
                    import java.lang.*;
                    // Any number of import statements
                    interface NameOfInterface
                    {
                           // Any number of final, static fields
                           // Any number of abstract method declarations
                    }
Example:

//Filename : Animal.java

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


Reasons For Using Interfaces in Java


◉ It allows us to achieve a complete abstraction.

◉ Interfaces are mainly designed to support dynamic method resolution at run time.

◉ Interfaces allow us to achieve loose coupling.

◉ It also helps us to separate the definition of a method from the inheritance hierarchy.

Implementing Interfaces


A class implementing an interface can be thought of as the class assigning a contract. This means that the class agrees to perform the specific behaviors of the Interface. Unless a class is declared as abstract, it should perform all the behaviors of the Interface.

In order to implement an Interface in Java, a class uses the implements keyword. The implements keyword appears in the class declaration after the extends portion of the declaration.

Code to understand Interfaces in Java:

package com.oraclejavacertified.interfaces;
interface Polygon
{
  //declaring variables of the interface
  public static final int length = 4,breadth = 8;
  //declaring interface methods(without a method body)
  public void getName();
  public void getNumberOfSides();
  public void getArea();
  public void getPerimeter();
}
// Rectangle class "implements" the Polygon interface
class Rectangle implements Polygon
{
  public void getName()
  {
    // The body of getName() is provided here
    System.out.println("The name of the Polygon is: Rectangle");
  }
  public void getNumberOfSides()
  {
    // The body of getNumberOfSides() is provided here
    System.out.println("There are 4 sides in a Rectangle");
  }
  public void getArea()
  {
    // The body of getArea() is provided here
    System.out.println("The Area of Rectangle is: " +length*breadth);
  }
  public void getPerimeter()
  {
    // The body of getPerimeter() is provided here
    System.out.println("The Perimeter of Rectangle is: " +2*(length + breadth));
  }
}
class InterfaceDemo
{
  public static void main(String[] args)
  {
    Rectangle rectangle = new Rectangle(); // Create a Rectangle object
    //calling methods of class Rectangle
    rectangle.getName();
    rectangle.getNumberOfSides();
    rectangle.getArea();
    rectangle.getPerimeter();
  }
}

Output:

The name of the Polygon is: Rectangle
There are 4 sides in a Rectangle
The Area of Rectangle is: 32
The Perimeter of Rectangle is: 24

Rules to be followed for Interface


◉ The class that implements the Interface should implement all the methods defined in the Interface.

◉ An Interface can also contain final variables.

Abstract Class vs Interface in Java


We will compare Abstract Class vs Interface on the basis of following parameters:

S.No Parameter  Abstract Class   Interfaces 
1 Keyword Used An abstract keyword is used to create an abstract class. An interface keyword is used to create an interface.
Type of variables  Abstract class in Java can have both final, non-final, static and non-static variables.  An interface can only have final and static variables that are declared by default.
final variables  An abstract class may or may not have variables declared as final   In interfaces, variables are by default declared as final. 
Access Modifiers  Abstract classes can have all access modifiers: public, protected, private and default.  No other access modifiers are allowed except the public access modifier. 
Type of Methods  An abstract class can have both abstract and non-abstract or concrete methods.  An interface can only have abstract methods. From version 8 of Java, the interface supports static and non-static methods too. 
Constructors  An abstract class can have constructors  An interface can not have constructors 
Multiple Inheritance  Abstract classes do not support Multiple Inheritance. A class can extend only a single abstract class but can implement multiple Java interfaces.  Interfaces support Multiple Inheritance. 
Implementation  We can extend an abstract class using the extends keyword.  We can implement an interface using the implements keyword. 
Speed  Fast  Slow as it requires extra indirection. 
10  When to use  To avoid independence  For Future enhancement 

When to use Abstract Class?


Consider using abstract classes in the following cases:

◉ If you have some related classes that need to share the same lines of code, then we put these classes in abstract classes.

◉ If there is a requirement of using access modifiers other than public such as protected and private for methods or fields.

◉ When there is a need for defining a state of an object because we need to define a non-static or non-final field.

When to use Interface?


Consider using an interface in the following cases:

◉ When you want to achieve 100% abstraction.

◉ If you want to achieve multiple inheritance, that is, implementing more than one interface.

◉ When you want to specify the behavior of a particular data type irrespective of who implements its behavior.

Related Posts

0 comments:

Post a Comment