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


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]+"
";             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);     } }

Updated on: 05-Mar-2020

109 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements