The general definition of abstraction is hiding the internal details and show only functionality to the end user. The best example of abstraction is an ATM machine, why because, when you use the ATM machine you don’t know what happen behind it.
Ways to achieve the abstraction in Java
In Java, you may perform abstraction in two ways.
- By abstract class
- By Interfact
Abstract class
By using abstract class you can achieve 0 to 100 % of abstraction, why because an abstract class can have the concrete method. You can create an abstract class by using the abstract keyword. And also you can use the abstract keyword to create abstract method. You cannot create the abstract method in non abstract class. And also you cannot directly create the instance of the abstract class. If you want to create an instance of abstract class you should extend that class into non abstract class and override the abstract method there. And create the instance of non abstract class where you want.
package com.samplecoder.abstraction;
public abstract class SampleAbstractClass {
SampleAbstractClass(){
// Constructor
}
public abstract void sampleAbstractmethod();
public void sampleConcreteMethod() {
System.out.println("concrete method in abstract class");
}
}
package com.samplecoder.abstraction;
public class SampleAbstractChildClass extends SampleAbstractClass{
@Override
public void sampleAbstractmethod() {
// TODO Auto-generated method stub
System.out.println("sampleAbstractmethod");
}
public static void main(String...arg) {
SampleAbstractClass object = new SampleAbstractChildClass();
object.sampleAbstractmethod();
object.sampleConcreteMethod();
}
}
Interface
By using interface, you can achieve the 100% of abstraction in Java, why because, in interface all the methods are abstract method by default, so not need to use the abstract keyword to create abstract method. The interface is a keyword used to create the interface in java. You cannot create the instance to interface similarly abstract class. You should create the implementation class for the interface class. And you can create the instance of the implementation class where you want.
package com.samplecoder.abstraction;
public interface SampleInterface {
public void print(String arg);
}
If you want to know the difference between the an abstract class and interface please visit here
3 Comments on “Abstraction”
Comments are closed.