Tuesday, March 24, 2015

Abstract class and method

Abstract class
A class that is declared using “abstract” keyword is known as abstract class. It may or may not include abstract methods which means in abstract class you can have concrete methods (methods with body) as well along with abstract methods ( without an implementation, without braces, and followed by a semicolon). An abstract class can not be instantiated (you are not allowed to create object of Abstract class).

Abstract method
Points to remember about abstract method:
1) Abstract method has no body.
2) Always end the declaration with a semicolon(;).
3) It must be overridden. An abstract class must be extended and in a same way abstract method must be overridden.
4) Abstract method must be in a abstract class.
Note: The class which is extending abstract class must override (or implement) all the abstract methods.
Example of Abstract class and method
abstract class Demo1{
   public void disp1(){
     System.out.println("Concrete method of abstract class");
   }
   abstract public void disp2();
}

class Demo2 extends Demo1{
   /* I have given the body to abstract method of Demo1 class
   It is must if you don't declare abstract method of super class
   compiler would throw an error*/  
   public void disp2()
   {
       System.out.println("I'm overriding abstract method");
   }
   public static void main(String args[]){
       Demo2 obj = new Demo2();
       obj.disp2();
   }
}
Output:
I'm overriding abstract method

No comments:

Post a Comment