Abstraction

  • Abstraction is a process of hiding the implementation details and showing only functionality to the user.
  • The class encapsulates data items and the funtions to promote abstraction.

How to achieve abstraction

There are two ways to achieve abstraction in java

  • Abstract class 
  • Interface 

 

Abstract Class

  • A class that is declared as abstract is known as abstract class.
  • It needs to be extended and its method implemented. It cannot be instantiated.

Example

abstract class class_name{}

 

Abstract Method

  • Method that are declared without any body within an abstract class are called abstract method.
  • The method body will be defined by its subclass.
  •  Abstract method can never be final and static.
  • Any class that extends an abstract class must implement all the abstract methods declared by the super class.

Example

abstract void printStatus();//no body and abstract 

Example of abstract class and abstract method 

 abstract class Bike{
 abstract void run(); 
 }
 class Honda4 extends Bike{ 
 void run(){
 System.out.println("running safely..");
 }
 public static void main(String args[]){
 Bike obj = new Honda4();
 obj.run();
 }
 }

Output

running safely..

Example

abstract class Shape{
abstract void draw();
}
class Rectangle extends Shape{
void draw(){
System.out.println("drawing rectangle");
}
}
class Circle1 extends Shape{
void draw(){
System.out.println("drawing circle");
}
}
class TestAbstraction
{
public static void main(String args[]){
Shape s=new Circle1();
s.draw();
}
}

Output

drawing circle