Sunday, May 5, 2013

Write a java program to create an abstract class named Shape that contains an empty method named numberOfSides ( ).Provide three classes named Trapezoid, Triangle and Hexagon such that each one of the classes extends the class Shape. Each one of the classes contains only the method numberOfSides ( ) that shows the number of sides in the given geometrical figures.



abstract class Shape
{
    abstract int numberOfSides();
}

class Trapezoid extends Shape
{
    private static int sides=4;
    int numberOfSides()
    {
        return sides;
    }
    public String toString()
    {
        return "Trapezoid";
    }
}

class Triangle extends Shape
{
    private static int sides=3;
    int numberOfSides()
    {
        return sides;
    }
    public String toString()
    {
        return "Triangle";
    }
}

class Hexagon extends Shape
{   
    private static int sides = 6;
    int numberOfSides()
    {
        return sides;
    }
    public String toString()
    {
        return "Hexagon";
    }
}

public class Shapes
{
    public static void main(String args[])
    {
    Shape[] shapes = new Shape[4];
    Trapezoid tp = new Trapezoid();
    Triangle tr = new Triangle();
    Hexagon hx = new Hexagon();
    shapes[0]=tp;
    shapes[1]=tr;
    shapes[2]=hx;
    for(int i=0 ; i<3 ;i++)
    {
        System.out.println(shapes[i].toString()+" #sides:"+shapes[i].numberOfSides());

    }

    }
}

Output:


E:\javamani>java Shapes
Trapezoid #sides:4
Triangle #sides:3
Hexagon #sides:6

0 comments:

Post a Comment

Twitter Delicious Facebook Digg Stumbleupon Favorites More