Pages

Friday, August 3, 2012

Abstract Class

Abstract class is a class which contains methods without implementation.
If a class contains even a single abstract method you need to declare your class as abstract
like this
abstract class <classname>                          
{                                                                  
       //abstract methods                                
}                                                                  
Abstract class can't be instantiated because an abstract class contains abstract methods without definitions so creating object for such a class is meaningless.
Any subclass of an abstract class must provide the definition for the all the abstract methods of it's super class or declare itself also as abstract.

Now the question is
Q) Why we need an Abstract method  ?
Answer:
If you are unable to decide the exact definition of a method,lets take an example like if there is a method area() in your class,i bet you will get confused while providing definition for this method.you will definitely think whose area you are going to compute in this method either rectangle,triangle or circle ?
and finally you will come up with abstract area() so that any subclass of your abstract class will provide the definition of area() according to the requirement.

i am taking an example of an Automobile class


abstract class Car
{
int price;
String manufacturer;
public void display()
{
        System.out.println("its a car");
}
abstract public String getPrice();

}

class Bmw extends Car
{
        public String getPrice()
        {
                return "40 lacs";
         }

}
class Hyundai extends Car
{

        public String getPrice()
        {
                return "10 lacs";
         }
}

public class mainclass
{
         public static void main(String args[])
         {
                  Bmw car1=new Bmw();
                  Hyundai car2=new Hyundai();
                  car1.display();
                  car1.getPrice();
                car2.display();
                  car2.getPrice();
          }
}


in this example getPrice() method is abstract method in the Car class which is abstract itself.
getPrice() is overrided in the subclasses Bmw and Hyundai.


No comments:

Post a Comment