I know there are many pages to this question, but I cannot figure it out in my case.
I need to print an array of objects. For example, I have an array of objects that contain objects from the shape class. Am I calling the toString method for each object in an array, or the toString method code in an ObjectList to print instance variables? If so, how to do it?
public class Shape{
private String shapeName;
private int numSides;
public String toString(){
return shapeName + " has " + numSides + " sides.";
}
}
public class ObjectList{
private Object[] list = new Object[10];
private int numElement = 0;
public void add(Object next){
list[numElement] = next;
}
public String toString(){
}
}
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(square);
list.toString();
}
I am going to print this:
square has 4 sides
hexagon has 6 sides
source
share