手记

现有抽象类Shape,用Rectangle矩形和Circle圆形子类,求图形的周长与面积

Shape.java

package project2.second;
public abstract class Shape {
    public abstract double perimetre(double length,double width,double radius);
    public abstract double area(double length,double width,double radius);
}

Rectangle.java

package project2.second;
public class Rectangle extends Shape {

    @Override
    public double perimetre(double length,double width,double radius) {
        // TODO Auto-generated method stub
        double c1=2*(length+width);
        return c1;
    }
    @Override
    public double area(double length,double width,double radius) {
        // TODO Auto-generated method stub
        double s1=length*width;
        return s1;
    }
}

Circle.java

package project2.second;
public class Circle extends Shape {
    double pi=3.14;

    @Override
    public double perimetre(double length,double width,double radius) {
        // TODO Auto-generated method stub
        double c2=2*pi*radius;
        return c2;
    }
    @Override
    public double area(double length,double width,double radius) {
        // TODO Auto-generated method stub
        double s2=radius*radius*pi;
        return s2;
    }

}

Initial.java

package project2.second;
import java.util.Scanner;
/*现有抽象类Shape
 * 有Rectangle矩形和Circle圆形子类
 * 求图形的周长与面积*/
public class Initial {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        System.out.println("请输入矩形的长:");
        Scanner input1=new Scanner(System.in);
        double length=input1.nextDouble();
        System.out.println("请输入矩形的宽:");
        Scanner input2=new Scanner(System.in);
        double width=input2.nextDouble();
        Shape rectangle=new Rectangle();
        double s1=rectangle.area(length, width, 0);
        double c1=rectangle.perimetre(length, width, 0);
        System.out.println("矩形面积:"+s1);
        System.out.println("矩形周长:"+c1);

        System.out.println("请输入圆形的半径:");
        Scanner input3=new Scanner(System.in);
        double radius=input3.nextDouble();
        Shape circle=new Circle();
        double s2=circle.area(0, 0, radius);
        double c2=circle.perimetre(0, 0, radius);
        System.out.println("圆形面积:"+s2);
        System.out.println("圆形周长:"+c2);
    }

}
17人推荐
随时随地看视频
慕课网APP

热门评论

很不错,把所学知识全都结合到了一块

查看全部评论