Friday 26 June 2015

Abstract Class in java

Abstract Class 

Abstract class is a class that contains one or more abstract methods and the methods are only declared not defined.

Abstract class is used to implement the concept of method Overriding. Method Overriding means defining methods with same signature in base and subclass.

We define One Base class and define it as abstract class.Also, We define two sub classes of that base class by using "extends" Keyword. Create Reference of Base class and assign the object to that reference to call the methods of subclass. Like, in C++ we used to achieve this affect by creating pointer of base class and assigning it the address of subclass object to call the appropriate method using "->" operator.

For more Details Refer following link:

Abstract class

Example:


                                                      Fig : Abstract class 

Here, shape class is a abstract class containing one abstract method getArea(). Signature of this method is same in super and sub class. Subclass extends the super class and should define the getArea() method by using public keyword.

Code:

class CalculateAreas
{
    public static void main(String arg[])
    {
Shape s;
        Rectangle rect = new Rectangle(5.25, 4.0);
        s=rect;   //assigning object of subclass to superclass referance
        System.out.println("Area of rectangle is " + s.getArea());

        Circle circle = new Circle(7.5);
        s=circle; //assigning object of subclass to superclass referance
        System.out.println("Area of circle is " + s.getArea()); //calling method using reference of superclass
    }
}

abstract class Shape
{
    abstract double getArea(); // LINE A
}

class Rectangle extends Shape
{
    double length;
    double breadth;

    Rectangle(double length, double breadth)
    {
        this.length = length;
        this.breadth = breadth;
    }

    double getArea()
    {
        return length * breadth;
    }
}

class Circle extends Shape
{
    double radius;

    Circle(double radius)
    {
        this.radius = radius;
    }

    double getArea()
    {
        return 3.14 * radius * radius;
    }
}

OUTPUT:
Area of rectangle is 21.0
Area of circle is 176.625


For more Details Refer following link: