接口的使用

来源:互联网 发布:视频音量调节软件 编辑:程序博客网 时间:2024/05/16 15:35
创建接口Shape2D,其中定义常量PI为3.14并定义周长与面积的计算方法grith()和area()
创建Cricle类实现接口Shape2D,重写其中的方法
创建Rectangle类实现接口Shape2D,重写其中的方法
创建InterfaceExample类实现图形的周长、面积的计算并在控制台输入

Shape2D:
public interface Shape2D {
final double PI=3.14;
double grith();
double area();
}

Cricle类:
public class Cricle implements Shape2D{
public Cricle(){

}
int r;//半径
public Cricle(int i){
this.r=i;
}
public double grith() {
return 2*PI*r;
}
public double area() {
return PI*r*r;
}
}

Rectangle类:
public class Rectangle implements Shape2D {
public Rectangle(){
}
int length;//长
int width;//宽
public Rectangle(int j,int k){
this.length=j;
this.width=k;
}
public double grith() {
return (length+width)*2;
}
public double area() {
return length*width;
}
}

InterfaceExample类:
import java.util.Scanner;
public class InterfaceExample {
public static void main(String[] args){
Scanner input=new Scanner(System.in);
System.out.print("请输入圆的半径:");
int i=input.nextInt();
Cricle test=new Cricle(i);
System.out.println("圆的周长为:"+test.grith());
System.out.println("圆的面积为:"+test.area());

System.out.println("请输入长方形的长:");
int j=input.nextInt();
System.out.println("请输入长方形的宽:");
int k=input.nextInt();
Rectangle test1=new Rectangle(j,k);
System.out.println("圆的周长为:"+test1.grith());
System.out.println("圆的面积为:"+test1.area());

}


}
0 0