Java

                                   Need of Abstract classes and Interfaces in Java


What is Abstraction ?

Abstraction is a process of hiding the internal implementation details and showing only functionality to the user. It shows only essential things to the user and hides the internal details.   

eg. As in the car case relevant parts like steering, gear, horn, accelerator, breaks, etc. are shown to driver because they are necessary for driving. But the driver need not know the internal functioning of engine, gear, etc. Thus, showing relevant data to the user and hiding implementation or details from the user is Abstraction.

What is Abstract class ?

An abstract class is a class which has the abstract keyword in its declaration. It should have atleast one abstract method. i.e., methods without a body. It can have multiple concrete methods.
Abstract classes allows to create blueproints for concrete classes. But the inheriting class should implement the abstract method. 
Abstract classes cannot be instantiated means we can't create an object of abstract class.

Reasons For Using Abstract Class :
  • Abstract classes offer default functionality for the subclasses.
  • Provides a template for future specific classes
  • Helps you to define a common interface for its subclasses
  • Abstract class allows code reusability.

Why we need an Abstract class ?

Suppose we have a class Animal that has a method sound() and the subclasses of it like DogLionHorseCat etc. Since the animal sound differs from one animal to another, there is no point to implement this method in parent class. This is because every child class must override this method to give its own implementation details, like Lion class will say “Roar” in this method and Dog class will say “Woof”.

So when we know that all the animal child classes will and should override this method, then there is no point to implement this method in parent class. Thus, making this method abstract would be the good choice as by making this method abstract we force all the sub classes to implement this method( otherwise you will get compilation error), also we need not to give any implementation to this method in parent class.

Since the Animal class has an abstract method, you must need to declare this class abstract.

Now each animal must have a sound, by making this method abstract we made it compulsory to the child class to give implementation details to this method. This way we ensures that every animal has a sound.


// Sample code for Abstract Class in Java

Abstract Class Syntax

abstract class name{
    // code
}
*Abstract class Example

//abstract parent class
abstract class Animal{
   //abstract method
   public abstract void sound();
}
//Dog class extends Animal class
public class Dog extends Animal{

   public void sound(){
	System.out.println("Woof");
   }
   public static void main(String args[]){
	Animal obj = new Dog();
	obj.sound();
   }
}

Output:

Woof

*Abstract class Declaration

//Declaration using abstract keyword
abstract class A{
   //This is abstract method
   abstract void myMethod();

   //This is concrete method with body
   void anotherMethod(){
      //Does something
   }
}


What is Interface ?

Interfaces are similar to Abstract class but all the methods of abstract type. The interface is a blueprint that can be used to implement a class. It does not contain any concrete methods. It can have methods and variables just like the class but the methods declared in interface are by default abstract. 

Also, the variables declared in an interface are public, static & final by default. An interface cannot be instantiated. However, classes that implement interfaces can be instantiated.

Reasons For Using Interfaces :

  • Interfaces are used to achieve abstraction.
  • Designed to support dynamic method resolution at run time.
  • It helps you to achieve loose coupling.
  • Allows you to separate the definition of a method from the inheritance hierarchy.

Why we need an Interface ?

  • It is used to achieve total abstraction. we can say 100% abstraction.
  • Since java does not support multiple inheritances in the case of class, by using an interface it can achieve multiple inheritances.
  • It is also used to achieve loose coupling.

// Sample code for Interface in Java

Interface Syntax

interface name{
//methods
}
*Interface Example

interface Pet {
    public void test();
}
class Dog implements Pet {
    public void test() {
        System.out.println("Interface Method Implemented");
    }
    public static void main(String args[]) {
        Pet p = new Dog();
        p.test();
    }
}

Output:

Interface Method Implemented

Abstract Class vs Interface

ParametersInterfaceAbstract class
Class typeAn interface can have only public abstract methods.An abstract class has protected and public abstract methods.
Abstract keywordIn an abstract interface keyword, is optional for declaring a method as an abstract.In an abstract class, the abstract keyword is compulsory for declaring a method as an abstract.
StructureAbstract methodsAbstract & concrete methods
Inheritance/ ImplementationA Class can implement multiple interfacesThe class can inherit only one Abstract Class
Access ModifiersThe interface does not have access modifiers. Everything defined inside the interface is assumed public modifier.Abstract Class can have an access modifier.
When to useIt is better to use interface when various implementations share only method signature. Polymorphic hierarchy of value types.It should be used when various implementations of the same kind share a common behavior.


Data fieldsthe interface cannot contain data fields.the class can have data fields.
Multiple Inheritance DefaultA class may implement numerous interfaces.A class inherits only one abstract class.
ImplementationAn interface is abstract so that it can’t provide any code.An abstract class can give complete, default code which should be overridden.
Use of Access modifiersYou cannot use access modifiers for the method, properties, etc.You can use an abstract class which contains access modifiers.
UsageInterfaces help to define the peripheral abilities of a class.An abstract class defines the identity of a class.


InheritanceAn interface can inherit multiple interfaces but cannot inherit a class.An abstract class can inherit a class and multiple interfaces.
Constructor or destructorsAn interface cannot declare constructors or destructors.An abstract class can declare constructors and destructors.
Limit of ExtensionsIt can extend any number of interfaces.It can extend only one class or one abstract class at a time.


Blog Written By

Sayali Patukale 
PrathameshKachkure 
Rahul Ekambaram 
Dhiraj Rathod 
Ritika Sisodiya


 


"We Hope That This Will Be Really Helpful To You "

Comments