Wednesday, 23 August 2017

Abstract class in Java

Abstract Class

A class that is declared with an "abstract" keyword, is known as an abstract class in java. It can have abstract and non-abstract methods both.
These are some important points need to remember: 

  • It needs to be extended.
  • Its method implemented.
  • It can't be instantiated.
Example:
abstract class Demo{ }

Abstract method

A method that is declared as abstract, is known as an abstract method and it does not have an implementation.

Do you know, what does implementation means here?
It means method doesn't have body 

Example:
abstract void display(){ }


Wrong Example:


Program to understand the concept of an abstract class and abstract method :

abstract class A
 {
    abstract void display();
 }

class Test extends A
 {
   void display()
    {
      System.out.println("Hello World");
     }
   public static void main(String args[])
   {
     A obj = new Test();
     obj.display();
    }
 } 

OUTPUT:

Hello World

Important Points:

  • If there is any abstract method in a class, then that class must be abstract.
  • If you are extending an abstract class that has an abstract method, we must have to provide an implementation of the method or make this class as abstract.

2 comments: