Java试验--类和对象

来源:百度知道 编辑:UC知道 时间:2024/05/13 05:47:17
设计长方形类,成员变量包括长方形的长和宽。类中有计算面积和周长的方法,并有相应的set和get方法设置和获得长方形的长和宽。编写测试类是否达到预定功能(要求分别通过一个无参构造函数和一个有参数的构造函数初始化两个对象并打印输出其长和宽,面积和周长。

输出:
实例1:
长 : 10
宽 : 5
面积 : 50
周长 : 30
实例2:
长 : 20
宽 : 10
面积 : 200
周长 : 60

// 设计长方形类
class Rentangle {

// 无参构造函数
public Rentangle() {
}

// 有参数的构造函数
public Rentangle(long height, long width) {
this.height = height;
this.width = width;
}

// 长
private long height;

// 宽
private long width;

public long getHeight() {
return this.height;
}

public long getWidth() {
return this.width;
}

public void setHeight(long height) {
this.height = height;
}

public void setWidth(long width) {
this.width = width;
}

// 面积
public long area() {
return this.height * this.width;
}

// 周长
public long circumference() {
return 2