In: Computer Science
Create a generic method to print objects in java. Include a tester class.
Here we will create a class employee and we will declare instance variables for the class along with getter and setter.
All the comments are written in he codes to have a better understanding of the program.
We have two classes :-
1. Employee
2. Tester
In tester class we have created a generic method to call the objects of the employee class.
Codes for the employee class:
public class Employee {
//Instance variables of the class
private Integer id;
private String name;
//Setter and getter methods for the instance variables
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
//override the toString class for a better and customised output view
@Override
public String toString(){
return "Employee ID = " + id +", name = " +name;
}
}
Codes for the Tester class:
public class Tester {
public static void main(String[] args){
//Creating 2 objects of employee class
Employee e1 = new Employee();
e1.setId(123);
e1.setName("Danny");
Employee e2 =new Employee();
e2.setId(1234);
e2.setName("Robert");
//creating an array of Employee and assigning the objects of employee to it
Employee empArray[] =new Employee[2];
empArray[0]= e1;
empArray[1]= e2;
//calling the display method which is a generic method to display the objects of the class.
display(empArray);
}
//creation of the generic method named display which takes an array as a parameter.
private static <E> void display(E[] elements){
for (E e: elements) {
System.out.println(e);
}
}
}
All the comments are written in the program for better understanding
The output of the program: