Pages - Menu

Wednesday 26 September 2012

Inheritance in java


Inheritance is one of the major object oriented concepts in java, in which the object of one class shows the properties of another class. In other words we can say that inheritance is the relationships between classes. Consider the following example. 
                              Here DRAW_SHAPE is a class, DRAW_CIRCLE and DRAW_ RECTANGLE are another two classes. All we know that Rectangle and Circles are basically coming under the category Shape.  That means if we create an object of the class DRAW_ CIRCLE or DRAW_ RECTANGLE it is possible to access all the members of the class SHAPE using that object. Or we can say that SHAPE is the super class or parent class of the two classes DRAW_ RECTANGLE and DRAW SHAPE.
          
In java the "extends" keyword is used for inheritance. All the child classes  extends the parent class. The parent class is also called the super class. The programmatic view of the above example is given bellow.


                        class DRAW_SHAPE
                        {

                        }

                        class DRAW_CIRCLE extends DRAW_SHAPE
                        {

                        }

                        class DRAW_REACTNGLE extends DRAW_SHAPE
                        {

                        }
Consider the following example to know more about inheritance in java

       
 class DrawShape
{
String shape;
DrawShape(String shape)
{
this.shape = shape;
}
public String finishDrawing()
{
return "Drawing of "+shape+" success";
}
}

  class DrawCircle extends DrawShape
{
        DrawCircle(String shape)
{
        super(shape);
}
public String draw()
{
        return "Drawing of circle started";
}
}

class DrawRectangle extends DrawShape
{
        DrawRectangle(String shape)
{
        super(shape);
}
public String draw()
{
        return "Drawing of rectangle started";
}
}

public class DrawingDemo
{
public static void main(String args[])
{
DrawCircle circle = new DrawCircle("Circle");
DrawRectangle rectangle = new DrawRectangle("Rectangle");
System.out.println(circle.draw());
System.out.println(rectangle.draw());
System.out.println(circle.finishDrawing());
 System.out.println(rectangle.finishDrawing());
}
}
        





Here is the output of the program:

No comments:

Post a Comment