
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Achieve Abstraction Using Interfaces in Java
Abstraction is a process of hiding the implementation details from the user, only the functionality will be provided to the user. In other words, the user will have the information on what the object does instead of how it does it.
Since all the methods of the interface are abstract and the user doesn’t know how a method is written except the method signature/prototype. Using interfaces, you can achieve (complete) abstraction.
Abstraction in interfaces
An interface in Java is a specification of method prototypes. Whenever you need to guide the programmer or, make a contract specifying how the methods and fields of a type should be you can define an interface.
To create an object of this type you need to implement this interface, provide a body for all the abstract methods of the interface and obtain the object of the implementing class.
The user who want to use the methods of the interface, he only knows the classes that implement this interface and their methods, information about the implementation is completely hidden from the user, thus achieving 100% abstraction.
Example
interface Person{ void dsplay(); } class Student implements Person{ public void dsplay() { System.out.println("This is display method of the Student class"); } } class Lecturer implements Person{ public void dsplay() { System.out.println("This is display method of the Lecturer class"); } } public class AbstractionExample{ public static void main(String args[]) { Person person1 = new Student(); person1.dsplay(); Person person2 = new Lecturer(); person2.dsplay(); } }
Output
This is display method of the Student class This is display method of the Lecturer class