第四周课程总结&试验报告(二)

一。写一个名为Rectangle的类表示矩形。其属性包括宽width、高height和颜色color,width和height都是double型的,而color则是String类型的。要求该类具有:
(1) 使用构造函数完成各属性的初始赋值
(2) 使用get…()和set…()的形式完成属性的访问及修改
(3) 提供计算面积的getArea()方法和计算周长的getLength()方法。
代码:
package test;

class Rectangle{
private double width,height;
private String color;
public Rectangle(String color,double width,double height){
this.setColor(color);
this.setWidth(width);
this.setHeight(height);
}
public void getArea(){
System.out.println("面积:"+getWidth()getHeight());
}
public void getLength(){
System.out.println("周长:"+2
(getWidth()+getHeight()));
}
public void getColorN(){
System.out.println("颜色:"+getColor());
}
public String getColor(){
return color;
}
public void setColor(String color){
this.color=color;
}
public double getWidth(){
return width;
}
public void setWidth(double w){
width=w;
}
public double getHeight(){
return height;
}
public void setHeight(double h){
height=h;
}

 public static void main(String[] args) {
     Rectangle re=new Rectangle("red",15.01,22.22);

     re.getArea();          
     re.getLength();
     re.getColorN();
}

}


总结:该题自己先按照书上打,遇到一些问题:例如有两个color如何区别它们,以及公共类名的设立;后来在隔壁宿舍同学的帮助下解决了这些错误。
这次的实验主要是让我们掌握类的定义,熟悉属性、构造函数、方法的作用;掌握用类作为类型声明变量和方法返回值,理解类和对象的区别以及构造函数的使用,熟悉通过对象名引用实例的方法和属性。
第二题还没做出来,做出来了我再改。。。

原文地址:https://www.cnblogs.com/FLZ1208/p/11551065.html