Tuesday, 21 January 2014

ABSTRACT CLASSES AND METHODS IN JAVA

How to declare abstract class and abstract methods in java 

USING ABSTRACT CLASSES


A class which can not be instantiated is known as abstract class.If a class contain any abstract method then the class is declared as abstract method.It must be overridden. An abstract class must be extended and in a same way abstract method must be overridden.Abstract method has no body,it  always end the declaration with a semicolon(;).

Syntax of abstract methods:

Specifying abstract keyword before the class during declaration, makes it abstract.

abstract class AbstractDemo
{
   public void myMethod()
{
      //Statements here
   }
}

USING ABSTRACT METHODS


Method that are declared without any body within an abstract class is known as abstract method.The method body will be defined by its subclass.Abstract method can never be final and static.Any class that extends an abstract class must implement all the abstract methods declared by the super class.If you declare an abstract method  in a class then you must declare the class abstract as well. you can’t have abstract method in a non-abstract class. It’s vice versa is not always true: If a class is not having any abstract method then also it can be marked as abstract.

Syntax of abstract methods:

public abstract void display();

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