InterviewSolution
Saved Bookmarks
| 1. |
Association in Java |
|
Answer» A RELATIONSHIP between two CLASSES that can be ESTABLISHED using their OBJECTS is known as association in Java. The two forms of association are Composition and Aggregation. The types of association can be one-to-one, many-to-one, one-to-many, many-to-many etc. A program that demonstrates association in Java is given as follows: class Teacher { private String name; private int age; private String subject; Teacher(String name, int age, String subject) { this.name = name; this.age = age; this.subject = subject; } public String retTeacherName() { return this.name; } public String retTeacherSubject() { return this.subject; } } class Student { private int rno; private String name; Student(int rno, String name) { this.rno = rno; this.name = name; } public String retStudentName() { return this.name; } } public class Association { public static void main (String[] args) { Teacher t = new Teacher("Amy", 25, "Maths"); Student s1 = new Student(12, "John"); Student s2 = new Student(15, "Susan"); System.out.println(t.retTeacherName() + " teaches " + t.retTeacherSubject() + " to students " + s1.retStudentName() + " and " + s2.retStudentName()) ; } }The output of the above program is as follows: Amy teaches Maths to students John and SusanIn the above program, the two classes Teacher and Student are associated as a teacher may teach multiple students. This is a one-to-many relationship. |
|