Association Between Classes

This program demonstrates association between classes.

Problem Statement

Write a Java program where Library class contains Book objects.

Source Code

1 class Book {
2 String title;
3 Book(String t){ title=t; }
4 }
5 class Library {
6 Book book;
7 Library(Book b){ book=b; }
8 void showBook(){ System.out.println("Library has book: "+book.title); }
9 }
10 public class ClassAssociation {
11 public static void main(String[] args) {
12 System.out.println("Eduinq Class Association");
13 Book b=new Book("Java Programming");
14 Library l=new Library(b);
15 l.showBook();
16 }
17 }

Program Output

Eduinq Class Association
Library has book: Java Programming

Explanation

Association represents a relationship between two classes. - Library class holds a reference to Book object. - This demonstrates how objects can be linked together to model real world relationships in OOP. Conclusion: Shows how to implement association between classes.

Quick Links to Explore