Tuesday 18 September 2012

Java Practical - 8



    Program Definition 8 ::

     Define an abstract class called Polygon. Provide a constructor which takes an array of Cartesian Point as parameter. Also provide method called perimeter, which calculates and returns the perimeter of the Polygon. Declare abstract method area for this class. Also define a method called move, which takes two parameters x and y to specify the destination for the first point of the Polygon, and overload to make it work for Cartesian Point as a parameter. Now update the classes Triangle and Rectangle in the exercise 8 above, to be a subclass of the Polygon class. Write appropriate class with main method to test the polymorphism in the area method.




class CartesianPoint
{
int x, y;
CartesianPoint(int a)
{
x = y = a;
}
CartesianPoint(int a , int b)
{
x = a; y = b;
}

protected int getX()
{
return x;
}
protected int getY()
{
return y;
}
protected void move(int a)
{
x = y = a;
}
protected void move(int a, int b)
{
x = a; y = b;
}

public void display()
{
System.out.println("("+ x +", " + y + ")");
}
}

abstract class Polygon
{
CartesianPoint cp[];
Polygon(CartesianPoint c[])
{
cp = new CartesianPoint[ c.length ];
for(int i=0;i<c.length;i++)
{
cp[i]=c[i];
}
}
double perimeter()
{
double peri = 0,a[];
a = new double[cp.length];

for(int i = 0 ; i < cp.length ; i++)
{
if((i+1) < cp.length)
a[i]=Math.sqrt(Math.pow((cp[i].getX()-cp[i+1].getX()),2)+Math.pow((cp[i].getY()-cp[i+1].getY()),2));
else
a[i]=Math.sqrt(Math.pow((cp[i].getX()-cp[0].getX()),2)+Math.pow((cp[i].getY()-cp[0].getY()),2));
peri=peri+a[i];
}
return peri;
}

abstract public double area();

public void move(int x, int y)
{
cp[ 0 ].move( x, y);
}
public void move(CartesianPoint c)
{
cp[ 0 ].x = c.getX();
cp[ 0 ].y = c.getY();
}

}

class Triangle extends Polygon
{
Triangle( CartesianPoint c[] )
{
super(c);
}
public double area()
{
return ((Math.abs(cp[0].getX()*(cp[1].getY()-cp[2].getY()) + cp[1].getX()*(cp[2].getY()-cp[0].getY()) + cp[2].getX()*(cp[0].getY()-cp[1].getY()))/2));
}
public void display()
{
for ( int i = 0 ; i < 3 ; i++ )
{
cp[i].display();
}
}
}
class Prog8
{
public static void main(String args[])
{
CartesianPoint c[] = new CartesianPoint[ 3 ];
c[0] = new CartesianPoint(5,5);
c[1] = new CartesianPoint(10,5);
c[2] = new CartesianPoint(10,10);

Triangle T1 = new Triangle(c);

T1.display();

System.out.println("Area :: " + T1.area() );

}
}

/*

D:\JAVA >javac Prog8.java

D:\JAVA >java Prog8
(5, 5)
(10, 5)
(10, 10)
Area :: 12.0
*/


Kindly Bookmark and Share it:

0 comments :

Post a Comment

Any Query ? any suggestion ? comment here

 

Recent Post

Recent Comments

© 2010 IamLearningHere Template by MBT