定义接口DiagArea,其中包含方法double getDiagonal()求对角线长, double getArea()求面积,
public interface DiagArea{
public double getDiagonal();
public double getArea();
}
class Rectangle implements DiagArea
{
int w,h;
Rectangle(int a,int b)
{
w=a;
h=b;
}
public double getDiagonal()
{
return Math.sqrt(w*w+h*h);
}
public double getArea()
{
return w*h;
}
public void Display()
{
System.out.println("w= "+w+" h= "+h);
System.out.println("the Rectangle's diagoal is "+this.getDiagonal());
System.out.println("the Rectangle's area is "+this.getArea());
}
}
class Square implements DiagArea
{
int a;
Square(int a)
{
this.a=a;
}
public double getDiagonal()
{
return Math.sqrt(a*a*2);
}
public double getArea()
{
return a*a;
}
public void Display()
{
System.out.println("a= "+a);
System.out.println("the Square's diagoal is "+this.getDiagonal());
System.out.println("the Square's area is "+this.getArea());
}
}
class DiagDisplay
{
public static void main(String[] args)
{
Rectangle a=new Rectangle(3,4);
Square b=new Square(5);
a.Display();
b.Display();
}
}
----------------解决方案--------------------------------------------------------
[en] [en]
----------------解决方案--------------------------------------------------------