课后作业,不知道这样的功能行不行
父类:
package Duotai;
public abstract class Shape {
public abstract void perimeter(double x,double y);
public abstract void perimeter(double r);
public abstract void area(double x,double y);
public abstract void area(double r);
}
矩形:
package Duotai;
public class Rectangle extends Shape {
@Override
public void perimeter(double x, double y) {
// TODO Auto-generated method stub
double peri=2*x*y;
System.out.println("矩形的周长为:"+peri);
}
@Override
public void perimeter(double r) {
// TODO Auto-generated method stub
}
@Override
public void area(double x, double y) {
// TODO Auto-generated method stub
double area=x*y;
System.out.println("矩形的面积为:"+area);
}
@Override
public void area(double r) {
// TODO Auto-generated method stub
}
}
圆形:
package Duotai;
public class Circle extends Shape {
@Override
public void perimeter(double x, double y) {
// TODO Auto-generated method stub
}
@Override
public void perimeter(double r) {
// TODO Auto-generated method stub
double pi=3.14;
double peri=2*pi*r;
System.out.println("圆形的周长为:"+peri);
}
@Override
public void area(double x, double y) {
// TODO Auto-generated method stub
}
@Override
public void area(double r) {
// TODO Auto-generated method stub
double pi=3.14;
double area=pi*r*r;
System.out.println("圆形的面积为:"+area);
}
}
测试类:
package Duotai;
import java.util.Scanner;
public class Initail03 {
public static void main(String[] args) {
// TODO Auto-generated method stub
calculate();
}
public static void calculate(){
Shape Rec1=new Rectangle();
Shape Cir1=new Circle();
Scanner input=new Scanner(System.in);//创建Scanner对象
System.out.println("请输入图形:");
String shape=input.next();
switch(shape){
case "rectangle":
System.out.println("请输入矩形的长:");
double length=input.nextDouble();
System.out.println("请输入矩形的宽:");
double width=input.nextDouble();
Rec1.perimeter(length,width);
Rec1.area(length,width);
break;
case "circle":
System.out.println("请输入圆形的半径:");
double radius=input.nextDouble();
Cir1.perimeter(radius);
Cir1.area(radius);
break;
default:
System.out.println("输入有误,请输入正确图形");
calculate();
}
}
}