🎯问题:
(1)定义成员变量:长(int height),宽(int width);
(2)定义无参构造方法,带参构造方法;
(3)定义以上成员变量对应的getXxx()/setXxx()方法;以及一个显示所有成员信息的toString()方法;
(4)定义求周长的zhouChang()方法和求面积的area()方法;
(5)定义一个测试类RectangleDemo, 进行测试,分别用无参构造方法和带参构造方法创建对象,计算周长和面积。测试结果如下:
🎯 结果:
public class Java2{ private int height; private int width; public Java2() {//无参构造方法 } public Java2(int heingt,int width) {//有参构造方法 this.height=heingt; this.width=width; } public int getHeight() { return height; } public void setHeight(int height) { this.height = height; } public int getWidth() { return width; } public void setWidth(int width) { this.width = width; } @Override public String toString() { // TODO Auto-generated method stub return "Rectangle [ width="+width+",height="+height; } public int zhouChang() { return 2*(height+width); } public int area() { return height*width; } public static void main(String[] args) { // 创建无参构造方法的对象 Java2 rectangle1 = new Java2(); rectangle1.setHeight(10); rectangle1.setWidth(8); System.out.println(rectangle1.toString()); System.out.println("周长为:" + rectangle1.zhouChang()); System.out.println("面积为:" + rectangle1.area()); // 创建带参构造方法的对象 Java2 rectangle2 = new Java2(12, 9); System.out.println(rectangle2.toString()); System.out.println("周长为:" + rectangle2.zhouChang()); System.out.println("面积为:" + rectangle2.area()); } }