本文主要是介绍java面向对象的封装Rectangle,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
(1)定义矩形类Rectangle, * - 声明实例变量长和宽,全部私有化private, * - 提供相应的get/set方法,如果set方法的参数值<=0,则提示矩形的长和宽必须是正数 * - 声明public double area(),返回矩形面积 * - 声明public double perimeter():返回矩形的周长 * - 声明public String getInfo():返回矩形的长、宽、面积、周长信息
(2)测试类的main中创建一个可以装3个矩形对象的数组, * - 并调用set方法为对象的属性赋值,依次长是8,7,6,宽是2,3,4 * - 遍历输出矩形对象数组信息 * - 按照矩形对象的length属性值从小到大排序后,遍历输出矩形对象数组 * - 按照矩形对象的面积从小到大排序后,遍历输出矩形对象数组
public class Rectangle {private double length;private double height;public double getLength() {return length;}public void setLength(double length) {if (length <= 0) {System.out.println("矩形的长必须是正数!");return;}this.length = length;}public double getHeight() {return height;}public void setHeight(double height) {if (height <= 0) {System.out.println("矩形的宽必须是正数!");return;}this.height = height;}//矩形面积//可以不传递参数//用的是属性public double area() {return length * height;}//矩形周长public double perimeter() {return (length + height) * 2;}//矩形信息public String getInfo() {return "矩形的长是:" + length + "m," + "宽是:" + height + "m," + "面积是:" + area() + ",m" + "周长是:" + perimeter() + ",m";}
}
public class TestRectangle {public static void main(String[] args) {Rectangle[] rec = new Rectangle[3];//1.创建矩形数组rec,矩形数组中没有矩形对象,所以出现空指针异常//NullPointerException,解决方式如下://2.创建矩形数组中的矩形对象:for (int i = 0; i < rec.length; i++) {rec[i] = new Rectangle();}rec[0].setLength(8);rec[0].setHeight(2);rec[1].setLength(7);rec[1].setHeight(3);rec[2].setLength(6);rec[2].setHeight(4);//2.遍历输出矩形对象数组信息for (int i = 0; i < rec.length; i++) {System.out.println(rec[i].getInfo());}//按照矩形对象的length属性值从小到大排序后,遍历输出矩形对象数组//3.按照矩形对象的length属性值从小到大排序后,遍历输出矩形对象数组//冒泡排序for (int i = 0; i < rec.length - 1; i++) {double rel = 0;for (int j = 0; j < rec.length - i - 1; j++) {if (rec[j].getLength() > rec[j + 1].getLength()) {rel = rec[j].getLength();rec[j].setLength(rec[j + 1].getLength());rec[j + 1].setLength(rel);}}}for (int i = 0; i < rec.length; i++) {System.out.println(rec[i].getInfo());}//4.按照矩形对象的面积从小到大排序后,遍历输出矩形对象数组for (int i = 0; i < rec.length - 1; i++) {for (int j = 0; j < rec.length - i - 1; j++) {if (rec[j].area() > rec[j + 1].area()) {Rectangle rel1 = rec[j];rec[j] = rec[j + 1];rec[j + 1] = rel1;}}}for (int i = 0; i < rec.length; i++) {System.out.println(rec[i].getInfo());}}
}
这篇关于java面向对象的封装Rectangle的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!