Association
About
Types of Association
Type
Description
Example
Code Example: Association in Java
Example 1: One-to-One Association (A Person Has One Passport)
class Passport {
String passportNumber;
Passport(String passportNumber) {
this.passportNumber = passportNumber;
}
}
class Person {
String name;
Passport passport; // Association with Passport
Person(String name, Passport passport) {
this.name = name;
this.passport = passport;
}
void display() {
System.out.println(name + " has passport: " + passport.passportNumber);
}
}
public class Main {
public static void main(String[] args) {
Passport p1 = new Passport("A123456");
Person person1 = new Person("John", p1);
person1.display(); // Output: John has passport: A123456
}
}Example 2: One-to-Many Association (A Teacher Teaches Many Students)
Example 3: Many-to-Many Association (Students Enroll in Courses)
Example 4: Many-to-One Association (Multiple Students Study in One School)
Association vs. Aggregation vs. Composition
Last updated