=我给你写一个。从上往下类依次为:
1.描述一个矩形,包含有长、宽两种属性,和计算面积方法
public class Rectangle {
float width, height;
public float getArea() {
return width * height;
}
/**
* 改变矩形的大小
*
* @param w
* 宽度
* @param h
* 高度
*/
public void resize(float w, float h) {
width = w;
height = h;
}
}
2.继承自矩形类,同时该类描述长方体,具有长、宽、高属性,和计算体积的方
法
public class RectangleService extends Rectangle {
float width, height, gao;
Rectangle rectangle;
public void resize(float w, float h) {
// TODO Auto-generated method stub
rectangle.width = w;
rectangle.height = h;
}
public float getVolume() {
return rectangle.getArea() * gao;
}
/**
* @return the width
*/
public float getWidth() {
return width;
}
/**
* @param width
* the width to set
*/
public void setWidth(float width) {
this.width = width;
}
/**
* @return the height
*/
public float getHeight() {
return height;
}
/**
* @param height
* the height to set
*/
public void setHeight(float height) {
this.height = height;
}
/**
* @return the gao
*/
public float getGao() {
return gao;
}
/**
* @param gao
* the gao to set
*/
public void setGao(float gao) {
this.gao = gao;
}
/**
* @return the rectangle
*/
public Rectangle getRectangle() {
return rectangle;
}
/**
* @param rectangle
* the rectangle to set
*/
public void setRectangle(Rectangle rectangle) {
this.rectangle = rectangle;
}
}
3.测试类
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Rectangle r1 = new Rectangle();
r1.resize(4.0F, 3.0F);
RectangleService r2 = new RectangleService();
r2.setGao(2.0F);
r2.setRectangle(r1);
System.out.println("矩形1的面积:" + r1.getArea());
System.out.println("矩形1的体积:" + r2.getVolume());
}
}
public class Test{
public static void main(String args[]){
Rectangle r = new Rectangle(1, 2);
System.out.println(r.area());
Cuboid c = new Cuboid(1, 2, 3);
System.out.println(c.area());
System.out.println(c.volum());
}
}
class Rectangle {//矩形
protected double width;
protected double lng;
public double area(){
return lng * width;
}
public Rectangle(double lng, double width){
this.width = width;
this.lng = lng;
}
}
class Cuboid extends Rectangle{//长方体
private double height;
public Cuboid(double lng, double width, double height) {
super(lng, width);
this.height = height;
}
public double area(){//表面积
return (width * lng + width * height + lng * height)*2;
}
public double volum(){//体积
return super.width * super.lng * height;
}
}
-------------
2.0
22.0
6.0
打酱油。。。