Rectangle.java://////////////////////////////////////////
public class Rectangle
{
public double a;
public double b;
public String color;
// default constructor
public Rectangle()
{
a=1;
b=1;
color="red";
};
// constructor for square
public Rectangle(double aa, String ss)
{
a=aa;
b=aa;
color="red";
};
public Rectangle(double aa, double bb, String ss)
{
a=aa;
b=bb;
color=ss;
};
public double Perimeter()
{
return 2*(a+b);
};
public double Square()
{
return a*b;
};
public double Diagonal()
{
return Math.sqrt(a*a+b*b);
};
public void PrintInfo()
{
System.out.format("Rectangle: a=%f, b=%f, color is '%s'
", a,b,color);
System.out.format("Square = %f, Perimeter = %f, Diagonal = %f
", Square(),
Perimeter(), Diagonal());
};
};
//////////////////////////////////////////
TestRectangle.java:
//////////////////////////////////////////
public class TestRectangle extends Rectangle
{
public static void main(String[] args)
{
Rectangle R = new Rectangle();
Rectangle S = new Rectangle(2,4,"blue");
R.PrintInfo();
S.PrintInfo();
};
};
//////////////////////////////////////////
To run them use the following commands:
javac Rectangle.java
javac TestRectangle.java
java TestRectangle
The output it the following:
Rectangle: a=1,000000, b=1,000000, color is 'red'
Square = 1,000000, Perimeter = 4,000000, Diagonal = 1,414214
Rectangle: a=2,000000, b=4,000000, color is 'blue'
Square = 8,000000, Perimeter = 12,000000, Diagonal = 4,472136
Comments
Leave a comment