Friday, 27 October 2017

abstract keyword in java

What is abstract keyword

abstract keyword is used to implement the abstraction in java. A method which does not have method definition must be declared as abstract. You can't instantiate abstract classes. Abstract methods must be implemented in the sub classes. We can't use abstract keyword with variables and constructors.

What is abstract class

An abstract class is a class that is declared as abstract. It may or may not be include abstract method. If a class has at least one abstract method, then the class must be declared as abstract class. abstract classes cannot be instantiated , but they can be extended. If we extended an abstract class, we have to provide implementation to all the abstract methods in it.

What is abstract method

An abstract method is a method that is declared without an implementation.

Example 1:

public abstract int add(int a, int b);

An abstract method must always be declared in an abstract class or in other word we can say that if a class has an abstract method, it should be declared as abstract.

Now we will take one example to explain abstract class and abstract method

Example 2:


abstract class Add{

abstract public int add(int a, int b);


class Complete extends Add{

public int add(int a, int b){

return a+b;



public class Sum{

public static void main(String [ ]p){

Complete obj=new Complete( );

int c=obj.add(5,12);

System.out.println("addtion of two numbers is"+c);



Output of the program:

addition of two numbers is 17

Code Explanation:

In above program first we created an abstract class named as Add and it contains one abstract method add and then we created a class named as Complete that inherits the Add class. Complete class provide implementation to the abstract method of Add class. Now we create third class named as Sum. Inside this main class we create object of Complete class and by using the object we call the add method and it returns sum of the given values and we print the value.