A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 641113495 中级黑马   /  2015-9-13 22:15  /  885 人查看  /  1 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

//创建一个矩形面向对象,并求周长和面积
class Practise_Rectangle {                                                        //rectangle矩形
        public static void main(String[] args) {
                Rectangle rectangle = new Rectangle();                                //创建对象rectangle
                rectangle.setWidth(20);
                rectangle.setHigh(30);
                System.out.println("周长是:" + rectangle.getLength() + ",面积是:" + rectangle.getArea() );

                System.out.println("有参构造方法");
                Rectangle r1 = new Rectangle(60,5);                                        //创建对象r1
                System.out.println("周长是:" + r1.getLength() + ",面积是:" + r1.getArea() );
                int back1 = rectangle.getLength();                                //必须是对象(如:r1)调用方法
                int back2 = r1.getArea();
                System.out.println("周长是:" + back1 + ",面积是:" + back2);
        //输出  周长是:100,面积是:300   周长算的是对象rectangle中成员变量的   面积是对象r1中成员变量的
        }
}

/*
矩形:Rectangle
宽:width
高:high

求周长的方法: getLength()
求面积的方法: getArea()

*/

class Rectangle {
        private int width;                                                                //定义成员变量wigth:宽
        private int high;                                                                //定义成员变量high:高

        public Rectangle(){}                                                        //定义无参构造方法

        public Rectangle(int width,int high) {                        //定义有参构造方法
                this.width = width;
                this.high = high;
        }

        public void setWidth(int width) {                                //设置宽
                this.width = width;
        }

        public int getWidth() {                                                        //获取宽
                return width;
        }

        public void setHigh(int high) {                                        //设置高
                this.high = high;
        }

        public int getHigh() {                                                        //获取高
                return high;
        }

        public int getLength(){                                                        //定义方法求矩形的周长
                int length = (width + high) * 2;
                return length;
        }

        public int getArea() {                                                        //定义方法求矩形的面积
                int area = width * high;
                return area;
        }
}

1 个回复

倒序浏览
嗯,写的不错
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马