知方号

知方号

Java基础 接口实现 设计一个形状类(接口)Shape,方法:求周长和求面积<接口中抽象方法>

题目: 设计一个形状类(接口)Shape,方法:求周长和求面积形状类(接口)的子类(实现类);:Rect(矩形),Circle(圆形)Rect类的子类:Square(正方形)不同的子类会有不同的计算周长和面积的方法。 创建三个不同的形状对象,放在Shape类型的数组里,分别打印出每个对象的周长和面积。

形状接口

public interface Shape {// 求面积方法double getArea();// 求周长方法double getPerimeter();}

圆形类

public class Circle implements Shape {private final double PI = 3.14; //圆周率private double r; //半径public double getR() {return r;}public void setR(double r) {this.r = r;}public Circle(double r) {this.r = r;}@Overridepublic double getArea() {// TODO Auto-generated method stubreturn PI * r * r;}@Overridepublic double getPerimeter() {// TODO Auto-generated method stubreturn PI * r * 2;}}

矩形类

public class Rect implements Shape {private double width; // 宽private double height; // 高public double getWidth() {return width;}public void setWidth(double width) {this.width = width;}public double getHeight() {return height;}public void setHeight(double height) {this.height = height;}// 一个参数构造,给子类正方形用public Rect(double width) {this.width = width;}//两个参数的构造,自己用public Rect(double width, double height) {this.height = height;this.width = width;}@Overridepublic double getArea() {// TODO Auto-generated method stubreturn width * height;}@Overridepublic double getPerimeter() {// TODO Auto-generated method stubreturn 2 * (width + height);}}

正方形,继承矩形

public class Square extends Rect {public Square(double width) {super(width);}@Overridepublic double getArea() {// TODO Auto-generated method stubreturn getWidth() * getWidth();}@Overridepublic double getPerimeter() {// TODO Auto-generated method stubreturn 4 * getWidth();}}

测试类

public class Test {public static void main(String[] args) {Shape[] shape = new Shape[3];shape[0] = new Circle(3);System.out.println("========圆形周长和面积========");System.out.println(String.format("%.2f", shape[0].getArea()));System.out.println(shape[0].getPerimeter());shape[1] = new Rect(5, 8);System.out.println("========矩形周长和面积========");System.out.println(shape[1].getArea());System.out.println(shape[1].getPerimeter());shape[2] = new Square(5);System.out.println("========正方形周长和面积========");System.out.println(shape[2].getArea());System.out.println(shape[2].getPerimeter());}}

每天进步一点点!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至lizi9903@foxmail.com举报,一经查实,本站将立刻删除。