Abstraction is a process of hiding the implementation details from the user. Оnly the functionality will be provided to the user. Abstraction shows only important things to the user and hides the internal details.
For example, when we ride a bike, we only know about how to ride bikes but can not know about how it works? And also we do not know the internal functionality of a bike.
Abstraction in java is achieved by using the interface and abstract class. Interface give 100% abstraction and abstract class give 0-100% abstraction.
Abstract class in Java
A class containing the keyword abstract in its declaration creates the abstract class. It may or may not contain any abstract methods within it. When a class is classified as abstract, it cannot be instantiated. For using a class as abstract, it needs to be inherited from another class which has the abstract method implementation. It is to be noted that if a class has a minimum of one method as abstract, then the class has to be declared as abstract.
abstract class cycle
{
abstract void work();
}
class HeroCycle extends cycle
{
void work()
{
System.out.println(“Selling good”);
}
public static void main(String argu[])
{
cycle o = new HeroCycle();
o.work();
System.out.println(“Code executed”);
}
}
Abstract method
When a programmer wants any class having a specific method but also want the actual execution of that method to be resolute by its child classes, the methods can be declared in the base class in the form of abstract methods.
The keyword abstract is used for declaring abstract method.
The abstract keyword needs to be implemented before the name of the method.
The abstract method does not contain any method body.
If there are no curly braces given, there should have to be semicolon put at the end of the abstract method.
abstract class Sum
{
public abstract int sumOfTwo(int n1, int n2);
public abstract int sumOfThree(int n1, int n2, int n3);
public void disp()
{
System.out.println(“Method of class Sum”);
}
}
class Demo extends Sum
{
public int sumOfTwo(int num1, int num2)
{
return num1+num2;
}
public int sumOfThree(int num1, int num2, int num3)
{
return num1*num2*num3;
}
public static void main(String args[])
{
Sum obj = new Demo();
System.out.println(obj.sumOfTwo(3,7));
System.out.println(obj.sumOfThree(4, 3, 19));
obj.disp();
}
}
Note: An abstract class can have data member, abstract method, a method body, constructor and even main() method. If there is an abstract method in a class, that class must be abstract. If you are extending an abstract class that has an abstract method, you must either provide the implementation of the method or make this class abstract.