Java - Object-Oriented Programming (OOPS) Concept - Abstraction (Using abstract and interface) Tutorial
Abstraction is a process of showing only essential information to the user and hiding other internal detail (e.g function) which are not essential to show to the user.
For example.
Suppose a user is sending mail to another user and the user can only see the essential detail like mailto, message. but the user can’t see the function sending the mail to another user.
Abstract class and interface is been used in java to achieve abstraction.
- Using Abstract Class
A Class that is declared with an abstract keyword is known as abstraction. We cannot achieve 100% abstraction using abstract keyword.
- Abstract Class should contain a method with the body or abstract method i.e abstract void fly();
- If a method inside the class is declared abstract, then class also has to be declared abstract.
- If a class is declared abstract. then it cannot be instantiated.
- To use abstraction, we have to inherit child class from the parents class.
Implementation detail is provided by the non-abstract class, which is hidden from the user.
abstract class Bird{ //Parent Class
abstract void fly(); //use void fly(){}
}
public class Parrot extends Bird{ //Child Class
void fly(){
System.out.print("Parrot can Fly ");
}
public static void main(String args[]){
Bird p=new Parrot();
p.fly();
}
}
- Using Interface
The interface in java is similar to a class. We can achieve 100% abstraction using Interface.
With interface multiple inheritances are possible.
An interface cannot be instantiated like an abstract class.
In the interface, we can have constants, nested types, default and static methods.
To declare interfaces we can use the interface keyword, in place of class.
Interface fields are public, static, and final by default. And the methods are public and abstract.
In the below example, the Bird interface has only one method named fly(), and its implementation is given by Parrot Class.
interface Bird{ //Parent Class
void fly();
}
public class Parrot implements Bird{ //Child Class
public void fly(){
System.out.print("Parrot can Fly ");
}
public static void main(String args[]){
Parrot p=new Parrot();
p.fly();
}
}
Multiple inheritances
1] implements are used for inheritance between class and interface
2] extends are used for inheritance between two interfaces.
interface Bird1{ //Parent Class
void fly();
}
interface Bird2{//Parent Class
void eat();
}
public class Parrot implements Bird1,Bird2{ //Child Class
public void fly(){
System.out.println("Parrot can Fly ");
}
public void eat(){
System.out.println("Parrot can eat ");
}
public static void main(String args[]){
Parrot p=new Parrot();
p.fly();
p.eat();
}
}