package test;
//使用接口方式计算圆和正方形的面积和周长
interface Cal{
//定义圆周率
double PI = 3.14;
//求周长
public double getLong();
//求面积
public double getArea();
}
class Rectt implements Cal{
//边长
double r;
public Rectt(double r) {
this.r = r;
}
public double getLong(){
return 4*r;
}
public double getArea(){
return r*r;
}
}
class Circle implements Cal{
//半径
double r;
public Circle(double r) {
this.r = r;
}
public double getLong(){
return 2*r*Cal.PI;
}
public double getArea(){
return r*r*Cal.PI;
}
}
public class Demo1{
public static void main(String[] args) {
Rectt rect = new Rectt(10.0);
double rectLong = rect.getLong();
double rectArea = rect.getArea();
System.out.println("正方形的周长是:"+rectLong);
System.out.println("正方形的面积是:"+rectArea);
Circle c = new Circle(10.0);
double cLong = c.getLong();
double cArea = c.getArea();
System.out.println("圆的周长是:"+cLong);
System.out.println("圆的面积是:"+cArea);
}
}
转载自原文链接, 如需删除请联系管理员。
原文链接:JAVA--接口练习(求正方形和圆的周长、面积),转载请注明来源!