Creating multiple Java objects by one type only


You can create a List of object easily. Consider the following example, where I'll create an array of Employee objects and print their details in a for loop.

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

public class Tester implements Cloneable {
   private int data;

   public int getData() {
      return data;
   }
   public void setData(int data) {
      this.data = data;
   }
   public Tester(int data){
      this.data = data;
   }

   public static void main(String[] args) {
      List<Tester> testerList = new ArrayList<Tester>();

      testerList.add(new Tester(1));
      testerList.add(new Tester(2));
      testerList.add(new Tester(3));
      testerList.add(new Tester(4));

      for(Tester tester : testerList){
         System.out.println(tester.getData());
      }
   }
}

Updated on: 30-Jul-2019

976 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements