Java问题:声明一个接口,其中包含一个抽象方法。声明另一个类,将上述接口进行扩展(implements)。在类中实

2024-12-19 13:05:59
推荐回答(1个)
回答1:

package Test;
//形状类
abstract class Shape {

public abstract void getArea();

}
//矩形类
class Rectangle extends Shape{
float a;
float b;
public Rectangle(float a,float b){
this.a = a;
this.b = b;
}
public void getArea(){
float Area = a* b;
System.out.println("矩形的面积为:"+Area);
}
}
//三角形
class Triangle extends Shape{
float a;
float h;
public Triangle(float a,float h){
this.a = a;
this.h = h;
}
public void getArea(){
float Area=(a*h)/2;
System.out.println("三角形的面积为:"+Area);
}
}
//圆形
class Circle extends Shape{
float r;
public Circle(float r) {
this.r = r;
}
public void getArea(){
float Area=(float)(Math.PI*r*r);
System.out.println("圆形的面积为:"+Area);
}
}
//测试类
public class TestShape {

public TestShape(Shape s) {
s.getArea();
}
public static void main(String[] args) {
//矩形面积
Shape jx=new Rectangle(5,6);
TestShape ts=new TestShape(jx);

//三角形面积
Shape sjx=new Triangle(4,5);
TestShape ts1=new TestShape(sjx);

//圆形面积
Shape yx=new Circle(10);
TestShape ts2=new TestShape(yx);

}

}