Skip to Content
bytegarden

Relationships between Classes

  • There are 2 types of relationship between classes
    1. Inheritance
      • Generalization (parent-child relationship, “is-a” relationship)
      • Specialization (child class inherits and adds specific features)
    2. Association
      • Basic Association (objects are independent but related)
      • Aggregation (whole-part relationship, parts can exist independently)
      • Composition (stronger whole-part relationship, parts cannot exist independently)
      • Qualified Association (association with a qualifier attribute)

Inheritance

  • Inheritance is the process of acquiring features of an existing Class into a New Class
  • “is-a” relationship
  • A Class will have Properties and Method
  • For Example, A cylinder can acquire all the properties of circle Plus it can have extra feature. Where we can write a class cylinder inheriting from class circle

Generalization

  • Generalization is a form of inheritance that starts with specific classes (subclasses) and groups common features into a more general class (superclass)
  • In Generalization group of classes are referred with Super class with single name
  • Generalization means Bottom Up
  • In Generalization, a Super Class is made by grouping multiple Sub Classes
  • Can use Interfaces or Abstract Classes. The primary focus of generalization is usually creating a superclass. Interfaces focus more on defining common methods that need to be implemented, while generalization focuses on combining shared attributes and behaviors in a superclass
  • For example, if you have several classes like Dog, Cat, and Horse, they could all inherit from a more general class like Animal

Specialization

  • Specialization (also a form of inheritance) is the reverse, where you start with a general superclass and create more specific subclasses by adding unique features or behaviors
  • In Specialization a new Sub Class is Generated by borrowing the features of existing concrete class and adding new features to it
  • Specialization means Top Down
  • In specialization a new Class is derived from an existing Super Class
  • For example, a Dog class could be a specialized version of a more general Animal class

Association

  • Describes relationship between independent classes

  • Classes can exist independently of each other

  • Represents how objects interact or communicate with each other

  • Qualified Association: Uses a key to efficiently locate associated objects. The qualifier acts as a lookup key, typically implemented using a Map or Dictionary. For example, a Bank looking up accounts by account number

  • Cardinality of Association:

    1. Unidirectional: (One-way relationship). One class is aware but other is not. For eg, the Student class can be associated with the LibraryCard class, for the association where the student has a library card; a LibraryCard does not need to ‘know about’ a Student

        class LibraryCard {
          private int cardNumber;
          private Date expiryDate;
      
        // LibraryCard doesn't know about Student
        }
      
        class Student {
          private String name;
          private LibraryCard card; // Student knows about LibraryCard
      
          public void issueCard(LibraryCard card) {
            this.card = card;
          }
        }
    2. Bidirectional: (Two-way relationship). Classes are aware of each other and interact with one another. For eg, a Teacher class and a Classroom class may be associated bidirectionally; there would be a teacher assigned to a classroom, and a classroom would know to which teacher it is assigned

      class Doctor {
          private String name;
          private List<Patient> patients;  // Doctor knows their patients
      
          public void addPatient(Patient patient) {
              if (patients == null) {
                  patients = new ArrayList<>();
              }
              patients.add(patient);
          }
      }
      
      class Patient {
          private String name;
          private Doctor doctor;  // Patient knows their doctor
      
          public void assignDoctor(Doctor doctor) {
              this.doctor = doctor;
              doctor.addPatient(this);
          }
      }
  • Example of Association (BankAssociation.java, below). Also see this image for better understanding.
    bank employee association

    BankAssociation.java
    // Java Program to illustrate the Concept of Association
    import java.util.*;
    
    // Class 1
    // Bank class
    class Bank {
    
        // Attributes of bank
        private String bankName;
        private Set<Employee> employees;
    
        // Constructor of Bank class
        public Bank(String bankName) {
            this.bankName = bankName;
        }
    
        // Method of Bank class
        public String getBankName() {
            // Returning name of bank
            return this.bankName;
        }
    
        public void setEmployees(Set<Employee> employees) {
            this.employees = employees;
        }
    
        public Set<Employee> getEmployees() {
            return this.employees;
        }
    }
    
    // Class 2
    // Employee class
    class Employee {
    
        // Attributes of employee
        private String name;
    
        // Constructor of Employee class
        public Employee(String name) {
            // this keyword refers to current instance
            this.name = name;
        }
    
        // Method of Employee class
        public String getEmployeeName() {
            // returning the name of employee
            return this.name;
        }
    }
    
    // Class 3
    // Association between both the classes in main method
    public class BankAssociation {
    
        // Main driver method
        public static void main(String[] args) {
            // Creating Employee objects
            Employee emp1 = new Employee("Doyel");
            Employee emp2 = new Employee("Anish");
    
            // adding the employees to a set
            Set<Employee> employees = new HashSet<>();
            employees.add(emp1);
            employees.add(emp2);
    
            // Creating a Bank object
            Bank bank = new Bank("BOB");
    
            // setting the employees for the Bank object
            bank.setEmployees(employees);
    
            // traversing and displaying the bank employees
            for (Employee emp : bank.getEmployees()) {
                System.out.println(emp.getEmployeeName()
                        + " belongs to bank "
                        + bank.getBankName());
            }
        }
    }
    Runs in your browser with Java 21. Ctrl/⌘ + Enter to run.Built with CheerpJ
  • Link: Similar in concept but differ in their level of abstraction and context

AspectAssociationLink
LevelClass-level relationshipObject-level relationship
AbstractnessConceptual relationship between classesConcrete relationship between objects
TimeExists in design (static relationship)Exists at runtime (dynamic relationship)
ExampleStudent is related to CourseAlice (Student) is enrolled in Mathematics (Course)

Aggregation

Key Points:

  • Represents “has-a” relationship

  • Special form of Association

  • Container and contained objects can exist independently

  • Weaker relationship (loosely coupled) compared to Composition

  • Unidirectional in nature

  • Example of aggregation (InstituteManagement.java, below) Aggregation is denoted by this

    InstituteManagement.java
    // Java program to illustrate the Concept of Aggregation
    import java.util.*;
    
    // Class 1
    // Student class
    class Student {
    
        // Attributes of Student
        private String studentName;
        private int studentId;
    
        // Constructor of Student class
        public Student(String studentName, int studentId) {
            this.studentName = studentName;
            this.studentId = studentId;
        }
    
        public int getstudentId() {
            return studentId;
        }
    
        public String getstudentName() {
            return studentName;
        }
    }
    
    // Class 2
    // Department class
    // Department class contains list of Students
    @SuppressWarnings("unused")
    class Department {
    
        // Attributes of Department class
    
        private String deptName;
        private List<Student> students;
    
        // Constructor of Department class
        public Department(String deptName, List<Student> students) {
            this.deptName = deptName;
            this.students = students;
        }
    
        public List<Student> getStudents() {
            return students;
        }
    
        public void addStudent(Student student) {
            students.add(student);
        }
    }
    
    // Class 3
    // Institute class
    // Institute class contains the list of Departments
    @SuppressWarnings("unused")
    class Institute {
    
        // Attributes of Institute
        private String instituteName;
        private List<Department> departments;
    
        // Constructor of Institute class
        public Institute(String instituteName,
                List<Department> departments) {
            // This keyword refers to current instance itself
            this.instituteName = instituteName;
            this.departments = departments;
        }
    
        public void addDepartment(Department department) {
            departments.add(department);
        }
    
        // Method of Institute class
        // Counting total students in the institute
        @SuppressWarnings("unused")
        public int getTotalStudentsInInstitute() {
            int noOfStudents = 0;
            List<Student> students = null;
    
            for (Department dept : departments) {
                students = dept.getStudents();
    
                for (Student s : students) {
                    noOfStudents++;
                }
            }
            return noOfStudents;
        }
    }
    
    // Class 4
    // main class
    public class InstituteManagement {
    
        // main driver method
        public static void main(String[] args) {
            // Creating independent Student objects
            Student s1 = new Student("Parul", 1);
            Student s2 = new Student("Sachin", 2);
            Student s3 = new Student("Priya", 1);
            Student s4 = new Student("Rahul", 2);
    
            // Creating an list of CSE Students
            List<Student> cse_students = new ArrayList<Student>();
            cse_students.add(s1);
            cse_students.add(s2);
    
            // Creating an initial list of EE Students
            List<Student> ee_students = new ArrayList<Student>();
            ee_students.add(s3);
            ee_students.add(s4);
    
            // Creating Department object with a Students list
            // using Aggregation (Department "has" students)
            Department CSE = new Department("CSE", cse_students);
            Department EE = new Department("EE", ee_students);
    
            // Creating an initial list of Departments
            List<Department> departments = new ArrayList<Department>();
            departments.add(CSE);
            departments.add(EE);
    
            // Creating an Institute object with Departments list
            // using Aggregation (Institute "has" Departments)
            Institute institute = new Institute("BITS", departments);
    
            // Display message for better readability
            System.out.print("Total students in institute: ");
    
            // Calling method to get total number of students
            // in the institute and printing on console
            System.out.print(
                    institute.getTotalStudentsInInstitute());
        }
    }
    Runs in your browser with Java 21. Ctrl/⌘ + Enter to run.Built with CheerpJ

Characteristics:

  1. Container object doesn’t control lifetime of contained objects
  2. Objects can exist independently
  3. Contained objects can be shared among multiple containers
  4. Represents a part-whole relationship

Composition

Key Points:

  • Represents “part-of” relationship

  • Strong relationship (tightly coupled). Strongest form of association

  • Child (part) cannot exist without Parent (whole)

  • Parts are dependent on the whole

  • Lifetime of parts are controlled by whole

  • Example of composition (CompanyStructure.java, below)
    Composition is denoted by this

    CompanyStructure.java
    // Java program to illustrate the Concept of Composition
    
    import java.util.*;
    
    // Class 1
    // Department class
    class Department {
    
        // Attributes of Department
        public String departmentName;
    
        // Constructor of Department class
        public Department(String departmentName)
        {
            this.departmentName = departmentName;
        }
    
        public String getDepartmentName()
        {
            return departmentName;
        }
    }
    
    // Class 2
    // Company class
    @SuppressWarnings("unused")
    class Company {
    
        // Reference to refer to list of books
        private String companyName;
        private List<Department> departments;
    
        // Constructor of Company class
        public Company(String companyName)
        {
            this.companyName = companyName;
            this.departments = new ArrayList<Department>();
        }
    
        // Method
        // to add new Department to the Company
        public void addDepartment(Department department)
        {
            departments.add(department);
        }
    
        public List<Department> getDepartments()
        {
            return new ArrayList<>(departments);
        }
    
        // Method
        // to get total number of Departments in the Company
        public int getTotalDepartments()
        {
            return departments.size();
        }
    }
    
    // Class 3
    // Main class
    public class CompanyStructure {
    
        // Main driver method
        public static void main(String[] args)
        {
            // Creating a Company object
            Company techCompany = new Company("Tech Corp");
    
            techCompany.addDepartment(new Department("Engineering"));
            techCompany.addDepartment(new Department("Operations"));
            techCompany.addDepartment(new Department("Human Resources"));
            techCompany.addDepartment(new Department("Finance"));
    
            int d = techCompany.getTotalDepartments();
            System.out.println("Total Departments: " + d);
    
            System.out.println("Department names: ");
            for (Department dept : techCompany.getDepartments()) {
                System.out.println("- " + dept.getDepartmentName());
            }
        }
    }
    Runs in your browser with Java 21. Ctrl/⌘ + Enter to run.Built with CheerpJ
  • Characteristics:

    1. When parent is deleted, all child parts are deleted
    2. Child cannot belong to multiple parents
    3. Strong lifecycle dependency
    4. Denotes exclusive ownership
  • Difference b/w Association, Aggregation & Composition

FeatureAssociationAggregationComposition
DefinitionGeneral relationship between two classesA special form of association with a “has-a” relationshipA stronger form of association with a “part-of” relationship
DependencyClasses are related but can exist independentlyContained objects can exist independently of the container objectContained objects cannot exist without the container object
LifecycleIndependent lifecyclesIndependent lifecyclesDependent lifecycles
OwnershipNo ownership impliedShared ownershipExclusive ownership
StrengthWeakModerateStrong
CardinalityOne-to-one, one-to-many, many-to-one, many-to-manyOne-to-one, one-to-many, many-to-one, many-to-manyOne-to-one, one-to-many
ExampleTeacher and StudentLibrary and BooksCar and Engine
RepresentationUses a direct referenceUses a reference to the contained object(s)Contains instances of the contained object(s)
Illustrative Example Codejava class Teacher { private Student student; }java class Library { private List<Book> books; }java class Car { private Engine engine; }
  • This is a visual representation of association, aggregation, and composition
    Visual representation of association, aggregation, composition