Java--对象组合(画)
Main主类创建“红色”屋顶“白色”墙的房子、10米高的“银杏”树、20米长的“石头”桥、面积200平方米深3米的湖;创建一个画对象,通过构造方法把房子、树、 桥、湖组合进画中;调用show方法进行显示。
输入格式:
无需输入。
输出格式:
与样例一致。
输入样例:
输出样例:
这幅画中有:红色的屋顶,白色的墙10米高的银杏树20米长的石头桥200平方米的湖有3米深
代码实现:
class House{ private String roof; private String wall; public House(String roof,String wall){ this.roof=roof; this.wall=wall; } public String getRoof() { return roof; } public String getWall() { return wall; }}class Tree{ private int height; private String type; public Tree(int height,String type){ this.height=height; this.type=type; } public int getHeight() { return height; } public String getType() { return type; }}class Bridge{ private int length; private String stuff; public Bridge(int length,String stuff){ this.length=length; this.stuff=stuff; } public int getLength() { return length; } public String getStuff() { return stuff; }}class Lake{ private int area; private int depth; public Lake(int area,int depth){ this.area=area; this.depth=depth; } public int getArea() { return area; } public int getDepth() { return depth; }}class Picture{ private House house; private Tree tree; private Bridge bridge; private Lake lake; public Picture(House house, Tree tree, Bridge bridge, Lake lake) { this.house = house; this.tree = tree; this.bridge = bridge; this.lake = lake; } public void show(){ System.out.println("这幅画中有:"); System.out.println(house.getRoof()+"的屋顶,"+house.getWall()+"的墙"); System.out.println(tree.getHeight()+"米高的"+tree.getType()); System.out.println(bridge.getLength()+"米长的"+bridge.getStuff()+"桥"); System.out.println(lake.getArea()+"平方米的湖有"+ lake.getDepth()+"米深"); }}public class Main{ public static void main(String[] args) { House house = new House("红色","白色"); Tree tree = new Tree(10,"银杏树"); Bridge bridge = new Bridge(20,"石头"); Lake lake = new Lake(200,3); Picture picture = new Picture(house,tree,bridge,lake); picture.show(); }}
#看类图写程序的题不需要太多思考 主要是考验对写代码的熟练度