Abstraction is a process of hiding the implementation details and showing only functionality to the user.
Example: Suppose you want to call someone. You dialed his/her number and waiting to receive his/her response. You don’t know what the internal calling process. So calling someone is a data hiding process and this is called abstraction.
In java, there are 2 types of abstraction.
- Abstract class
- Abstract method
Without abstract class, abstract method cannot be declared.
Definition:
- Abstract class: Abstract class is a special type of class in java that is use only for creating abstract method. It can not be used to create object. To access the abstract class, it must be inherited from another class.
- Abstract method: Abstract method is a special type of method that only declare a method but without any body. A method without body is known as abstract method but abstract keyword should be use before the method. Abstract method is only used when needs to override the parent method.
Example: Suppose you want to find out the area of a rectangle, a circle, and a triangle. For every element, you want to find out the area but the area calculation formula of 3 elements are different. So you must have to use an abstract keyword before the area method.
Here is the code example:
class Main {
public static void main(String[] args) {
Rectangle rectangle=new Rectangle();
double rectangleArea=rectangle.findArea(5,8);
System.out.println("Area of rectangle is: "+rectangleArea);
Circle circle=new Circle();
double circleArea=circle.findArea(5);
System.out.println("Area of circle is: "+circleArea);
Triangle triangle=new Triangle();
double triangleArea=triangle.findArea(5,8,2);
System.out.println("Area of triangle is: "+triangleArea);
}
}
abstract class Elements{
public abstract double findArea(double r);
}
class Rectangle extends Elements{
public double findArea(double l, double w){
return l*w;
}
@Override
public double findArea(double r) {
return 0;
}
}
class Circle extends Elements{
public double findArea(double r){
double pi=3.1416;
return pi*r*r;
}
}
class Triangle extends Elements{
public double findArea(double l, double w, double h){
return l*w*h;
}
@Override
public double findArea(double r) {
return 0;
}
}
Output:
Area of rectangle is: 40.0
Area of circle is: 78.54
Area of triangle is: 80.0
Leave a Reply