How do you write a method in Java that can print object in array?

Java 8Object Oriented ProgrammingProgramming

Example

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);
    }
}
raja
Published on 22-Apr-2018 19:01:04
Advertisements