掌握类的定义,熟悉属性、构造函数、方法的作用,掌握用类作为类型声明变量和方法返回值;
理解类和对象的区别,掌握构造函数的使用,熟悉通过对象名引用实例的方法和属性;
理解static修饰付对类、类成员变量及类方法的影响。
1、写一个名为Rectangle的类表示矩形。其属性包括宽width、高height和颜色color,width和height都是double型的,而color则是String类型的。要求该类具有:
(1) 使用构造函数完成各属性的初始赋值
(2) 使用get…()和set…()的形式完成属性的访问及修改
(3) 提供计算面积的getArea()方法和计算周长的getLength()方法
package ectangle;
class Rectangle
{
private double heigh;
private double width;
private String color;
public Rectangle(double width,double heigh,String color) //使用构造函数
{
this.setWidth(width);
this.setHeigh(heigh);
this.setColor(color);
}
public void setWidth(double width)
{
this.width=width;
}
public double getWidth()
{
return width;
}
public void setHeigh(double heigh)
{
this.heigh=heigh;
}
public double getHeigh()
{
return heigh;
}
public void setColor(String color)
{
this.color=color;
}
public String getColor()
{
return color;
}
public double getArea() //计算面积
{
return this.width*this.heigh;
}
public double getLength() //计算周长
{
return 2*this.width+2*this.heigh;
}
}
public class Rectangle
{
public static void main(String args[])
{
Rectangle item = null;
item = new Rectangle(3,4,"red");
System.out.println(item.getColor());
System.out.println(item.getLength());
System.out.println(item.getArea());
}
}
原文:https://www.cnblogs.com/yuanqizhizhi/p/11556240.html