Abstraction is a concept in Object oriented programming where only required behavior and property will be shown/visible to the user/application.
In Java, data abstraction can be done in Java using abstract class / Interfaces.
Abstract Class are classes where we cannot create objects, however classes which are extending have to implement those functionalities, not defined in the abstract classes.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
public class AbstractionExample { public static void main(String[] args) { Calculator calculator = new AdvancedCalculator(); System.out.println("Addition Result:"); System.out.println(calculator.addition(5, 10)); System.out.println("Division Result:"); System.out.println(calculator.division(10, 0)); } } abstract class Calculator { public abstract int addition(int x, int y); public abstract int subtract(int x, int y); public abstract int multiply(int x, int y); public abstract int division(int x, int y); public boolean isValuesEqualToZero(int tmpValue) { if(tmpValue==0) { return true; } return false; } } class AdvancedCalculator extends Calculator { @Override public int addition(int x, int y) { return (x+y); } @Override public int subtract(int x, int y) { return (x-y); } @Override public int multiply(int x, int y) { return (x*y); } @Override public int division(int x, int y) { boolean result = isValuesEqualToZero(y); if(result) { System.out.println("[DivideByZero/Result is Infinity]"); return 0; } //Show result for infinity also as Zero.. return (x/y); } } |
In this abstract class we have abstract methods like addition,subtract,multiply & division., which are classes where any type of calculator should have.
However for a child class (like a LowLevelCalculator or AdvancedCalculator) to behave as a calculator, it needs to define addition,subtract,etc., methods.
For anybody who is using this calculator abstract class, default will have functionalities, however implementation will not be visible to User.
1 2 |
Calculator calculator = new AdvancedCalculator(); calculator.addition(9,10); |
Here calculator is a object, where it has the implementation of addition() method from AdvancedCalculator indirectly.