Creating multiple Java objects by one type only

Java Programming Java8Object Oriented Programming

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());
      }
   }
}
raja
Published on 23-Apr-2018 00:03:05
Advertisements