PREV NEXT
Abstraction:
- Abstraction is the process of hiding the inner details and showing the functionality.
- Abstraction can be achieved through abstract class or interface in Java.
Abstract class:
- A class which is declared as abstract is called abstract class. An abstract class may or maynot contain abstract methods.
- Abstract method is a method which has no implementation in it or a method without a body.
Example for Abstract method:
abstract void method(); |
Example for Abstract class:
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 |
abstract class Operation { //abstract class abstract void operate(int a, int b); // abstract method void display() { //ordinary method System.out.println(“Operation completed”); } } class Addition extends Operation { void operate(int a, int b) { System.out.println(“The addition of given numbers is:”+(a+b)); } class Subtraction extends Operation { void operate(int a,int b) { System.out.println(“The subtraction of given numbers is:”+(a-b)); } class calculate { public static void main(String args[]) { new Addition().operate(5,6); //calls operate method of Addition new Subtraction().operate(10,8); //calls operate method of Subtraction }} |
Output:
The addition of given numbers is:11 The subtraction of given numbers is:2 |
- Abstract class cannot be instantiated. It should only be implemented and used by the subclass.
- A subclass which inherits the abstract class either have to implement all the abstract methods present in the abstract class or declare itself as abstract.
- Every class contain its own variables and methods. Each and every object uses those variables and methods. Suppose if the object needs its own way to perform operations, then we need abstract class.
- Abstract class is a class which are declared abstract and cannot be instantiated. We cannot create object to an abstract class. We need subclasses which extents the abstract class to use it.
Consider you run a website where you teach how to play cricket, football, hocket etc. You are asking the learners to create a profile. Then you teach them the rules and regulations of the game and how to play the game.
1 2 3 4 5 6 7 8 9 10 11 |
class Sportsmen{ void createProfile{ } void howToPlay{ } } |
But all game doesn’t have same rules and same playing methods. So the body of the methods howToPlay() is left empty and is called abstract method.
Abstract method is a method which has no body. Then we create subclass called CricketPlayer to use the abstract method.
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 |
class CricketPlayer extends Sportsmen{ void createProfile{ } void howToPlay{ //code to teach cricket } } class FootBallPlayer extends Sportsmen{ void createProfile{ } void howToPlay{ //code to teach football } } |