Sunday 19 August 2012

What is a abstract class in java ?



There are situations in which we want to define a superclass that declares a structure of a given abstraction without providing a complete implementation of every method, i.e sometimes we want to create a superclass that only defines a generalised form that will be shared by all of its subclasses leaving it to each subclass to fill in the details. Any class that contains one or more abstract methods must also be declared abstract. To declare a class abstract we simply use the abstract keyword infront of the class keyword in the beginning of class declaration.
There can be no objects of an abstract class, i.e an abstract class cannot be directly instantiated with the new operator. Also you cannot declare abstract constructors or abstract stating methods. Any subclass of an abstract class must either implement all of the abstract methods in the superclass or be itself declared abstract.

For example :

abstract class A
{
        abstract void callme( );                  //abstract method that will 
                                                             //be defined in sub class
        void callmetoo( )
         {
              System.out.println(" This is a concrete method ") ;
          }
}

class B extends A
{
          void callme( )            //defination of abstract method
                                            // of super class
           {    
                 System.out.println("Implentation of callme in B");
            }
}

class C extends A
{
          void callme( )
          {
                 System.out.println("Implentation of callme in C");
           }
}
class AbstractDemo

            public static void main( String args [ ] )
            {
                   B b = new B( );
                   C c = new C( );
                   b.callme( );
                   b.callmetoo( );
                   c.callme( );
                   c.callmetoo( );
              }
 }



hence output of the above program will be:

Implentation of callme in B
This is a concrete method
Implentation of callme in C
This is a concrete method

No comments:

Post a Comment