您如何用Java编写可以在数组中打印对象的方法?
示例
class Shape{
private String shapeName;
private int numSides;
Shape(String shapeName, int numSides){
this.shapeName = shapeName;
this.numSides = numSides;
}
public String toString(){
return shapeName + " has " + numSides + " sides.";
}
}
class ObjectList{
private Object[] list = new Object[10];
private int numElement = 0;
public void add(Object next){
list[numElement] = next;
numElement++;
}
@Override
public String toString(){
String str="";
int i=0;
while(list[i] != null){
str += list[i]+"\n";
i++;
}
return str;
}
}
public class Driver{
public static void main(String[] args){
ObjectList list = new ObjectList();
Shape square = new Shape("square", 4);
Shape hex = new Shape("hexagon", 6);
list.add(hex);
list.add(square);
System.out.println(list);
}
}热门推荐
10 霸气新年祝福语大全简短
11 爱情红包祝福语简短英文
12 小孩生日祝福语简短励志
13 开业贺卡祝福语简短高级
14 家长会简短祝福语
15 默克尔离职祝福语简短
16 男生儿子生日祝福语简短
17 给钢琴老师简短祝福语
18 求婚蛋糕卡片祝福语简短