Chapter 3: Abstraction
What is Abstraction ?
Abstraction is a process of hiding the implementation details and showing only functionality to the user. i.e Hiding internal details and showing functionality is known as abstraction.
For example: Television, we don't know the internal processing, but we know its functionality and how to use it.
In java, there are two ways to achieve abstraction in java
- Abstract class
- Interface
Abstract Class
A class that is declared with abstract keyword is known as abstract class in java. It can have abstract methods (methods without body) and non-abstract methods (method with body).
Abstract class cannot be instantiated.
Example:
abstract class abs { }
Abstract Method
A method that is declared using abstract keyword and do not have implementation is known as abstract method.
Example:
abstract void add(); // no body , only method declaration.
Example of abstract class having abstract method.
abstract class Shape{ abstract void draw(); } //Implementation is provided by others i.e. hidden from end user class circle extends Shape{ void draw() { System.out.println("Draw Circle"); } } class rectangle extends Shape{ void draw() { System.out.println("Draw rectangle"); } } Class line extends shape { Void draw() { System.out.println(“Draw line”); } } class AbstractionTest { public static void main(String args[]) { shape s = new rectangle(); //Object of rectangle class (rectangle class instantiated) s.draw(); // draw() method is called with respect to rectangle class object } }
Note:
- Abstract class can have both abstract and non-abstract methods.
- Interface can have only abstract methods (Method without body, only declaration allowed).
Interface
The interface in java is a mechanism to achieve abstraction. There can be only abstract methods in the java interface not method body. It is used to achieve abstraction and multiple inheritances in Java.
Java Interface also represents IS-A relationship.
It cannot be instantiated just like abstract class.
Why Interface used:
- To support the functionality of multiple inheritances.
- To achieve abstraction.
The java compiler adds public and abstract keywords before the interface methods and it adds public, static and final keywords before data members.
Interface Example
Interface display { Void print(); // only method declaration, no body. } Class abc implements display { Void print () { // print method is implemented here. System.out.println(“print inside class abc”) ; } Public static void main(string args[]) { Abc obj = new abc(); Obj.print(); } }
Example: Multiple Inheritance in Java using Interface
interface display { void print(); } interface show { void print(); } class minheritance implements display, show{ public void print(){System.out.println("print method inside class minherit");} public static void main(String args[]){ minheritance obj = new minheritance (); obj.print(); } }