InterviewSolution
Saved Bookmarks
| 1. |
Composition in Java |
|
Answer» The two entities in composition are quite dependent on each other i.e. one ENTITY cannot exist without the other. Basically, composition is a restricted form of aggregation. A program that demonstrates composition in Java is given as follows: import java.io.*; import java.util.*; class DEPARTMENT { public STRING name; Department(String name) { this.name = name; } } class College { private final List<Department> departments; College (List<Department> departments) { this.departments = departments; } public List<Department> getDepartments() { return departments; } } public class Demo { public static void main (String[] args) { Department d1 = new Department("Computer Science"); Department d2 = new Department("Electrical"); Department D3 = new Department("Mechanical"); Department d4 = new Department("INFORMATION Technology"); Department d5 = new Department("Civil"); List<Department> departments = new ArrayList<Department>(); departments.add(d1); departments.add(d2); departments.add(d3); departments.add(d4); departments.add(d5); College c = new College(departments); List<Department> dpt = c.getDepartments(); System.out.println("The different departments in college are: "); for(Department d : dpt) { System.out.println(d.name); } } }The output of the above program is as follows: The different departments in college are: Computer Science Electrical Mechanical Information Technology CivilThe above program is an example of composition as the departments and college are dependent on each other. There would be no departments without a college. |
|