面向对象 计算长方形 周长,面积
定义长方形类,含:
属性:宽、高(浮点型);
方法:求周长、面积;
构造方法3个:(1)无参——宽、高默认值为1;(2)1个参数——宽、高均为参数值;2个(3) 3个参数——宽、高各为参数值。
要求:进行测试。
public class Test_ZuoYe5 {public static void main(String[] args) {//通过构造器传参Rectangle r=new Rectangle(4,6);System.out.println(r.area());System.out.println(r.perimeter());}
}class Rectangle{//属性double width;//宽double height;//高//空构造public Rectangle() {width=1;height=1;}//一个参数构造public Rectangle(double width) {this.width = width;this.height = width;}//全参构造public Rectangle(double width, double height) {this.width = width;this.height = height;}//求周长 长+高*2public double perimeter() {System.out.println("长方形的周长:");return (this.height + this.width) * 2;}//求面积 长*宽public double area(){System.out.println("长方形的面积:");return this.width*this.height;}}
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
