使用typora编辑博客(测试)
第一部分
[post.jfif](..\Pictures\post.jfif) package interfacedemo;
/**
* @classname:Interf
* @description:
* (1)定义shape接口,包含求面积和求周长的方法。 (2)定义Circle类、Rectangle类、Square类。
* (3)要求Circle类和Rectangle类实现shape接口,
* Square类继承Rectangle类。 运行时,让用户选择输入什么图形,然后输入相应数据,求出该图形的面积和周长。
*
*/
import java.util.Scanner;
interface shape{ //接口定义
double getArea();
double getCircumference();
}
class Circle implements shape{
private final double PI=3.14;
private double radius;
public Circle(double r)
{radius=r;}
//抽象方法实现
public double getArea() { //一个类在实现接口的抽象方法时,!必须!显式使用public修饰符
// TODO Auto-generated method stub
return PI*radius*radius;
}
public double getCircumference() { //一个类在实现接口的抽象方法时,!必须!显式使用public修饰符
// TODO Auto-generated method stub
return 2*PI*radius;
}
}
class Rectangle implements shape{
protected double width;
protected double height;
Rectangle(){}
Rectangle(double w,double h)
{
width=w;
height=h;
}
public double getArea() {
return width*height;
}
public double getCircumference() {
return 2*(width+height);
}
}
class Square extends Rectangle{
double side;
Square(double s)
{this.width=s;
this.height=s;
}
}
public class Interf {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc=new Scanner(System.in); //Scanner 输入
System.out.println("将要输入的图形为:");
String name =sc.next();
if(name.equals("圆形"))
{System.out.println("请输入半径:");
double r=sc.nextDouble();
System.out.println("圆形的周长为:"+new Circle(r).getCircumference()+" 面积为:"+new Circle(r).getArea()); //匿名
}
else if(name.equals("矩形"))
{System.out.println("请输入长和宽:");
double x,y;
x=sc.nextDouble();
y=sc.nextDouble();
Rectangle rec=new Rectangle(x,y); //非匿名
System.out.println("矩形的周长为:"+rec.getCircumference()+" 面积为:"+rec.getArea());
}
else if(name.equals("正方形"))
{System.out.println("请输入边长:");
double s=sc.nextDouble() ;
Square squa=new Square(s);
System.out.println("正方形周长为:"+squa.getCircumference()+" 面积为:"+squa.getArea());
}
else System.out.println("输入错误!");
sc.close();
}
}
第二部分