Java – Object Oriented Programming Concepts – Abstraction


Java – Abstraction

This is one of the key concepts in object oriented programming concepts.

What is the abstraction?

It is the process of displaying only essential things to the user.

Its main goal is to avoid complexity by hiding unnecessary details from the user.

Abstraction can be explained by abstract class and methods.

Abstract Class :

A class that is declared using “abstract” keyword is known as abstract class.

Limitations :

An abstract class can not be instantiated, which means you are not allowed to create an object of it.

Syntax :

abstract class ClassName{

}

Abstract Method :

An abstract method is declared using “abstract” keyword and does not have implementation is known as abstract method.

Syntax :

abstract void methodName();
{

}

Example 1 :


abstract class AbstractClass{
   public abstract void AbstractMethod();
}
public class ClassA extends AbstractClass{

   public void AbstractMethod(){
        System.out.println("Printing inside Abstract method");
   }
   public static void main(String args[]){
        AbstractClass obj = new ClassA();
        obj.AbstractMethod();
   }
}

Output :

Printing inside Abstract method


Why Object creation is not allowed in abstract class ?

There is no actual implementation of the abstract method to invoke.

An abstract class is like a template, so only we can extend it and build on it before you can use it.

An abstract class can not be instantiated, which means you are not allowed to create an object of it.

Example 1 :

abstract class AbstractClass{
   public void MethodName(){
      System.out.println("Hello");
   }
   abstract public void abstractMethod();
}
public class Eg1 extends AbstractClass{

   public void abstractMethod() { 
        System.out.print("Abstract method"); 
   }
   public static void main(String args[])
   { 
      AbstractClass obj = new AbstractClass();
      obj.abstractMethod();
   }
}

Output :

Eg1.java:14: error: AbstractClass is abstract; cannot be instantiated      

AbstractClass obj = new AbstractClass();                          

^1 error