Java – Has-A relation

Association:

  • Association is a relationship between two objects.
  • It’s denoted by “has-a” relationship.
  • In this relationship all objects have their own lifecycle and there is no owner.
  • In Association, both object can create and delete independently.
One to One:   One Customer Has One ID
                        One Menu Item has One ID
 
One to Many: One Customer can have number of Menu orders
 
Many to One: One Menu Item can be ordered by any number of Customers
 
Many to Many: N number of customers can order N menu items

Program implementation for following Has-A relation :

class Author
{
            String authorName;
            int age;
            String place;
 
            Author(String name, int age, String place)
            {
                        this.authorName = name;
                        this.age = age;
                        this.place = place;
            }
}
 
class Book
{
            String name;
            int price;
            Author auther;
            Book(String n, int p, Author auther)
            {
                        this.name = n;
                        this.price = p;
                        this.auther = auther;
            }
            void bookDetails()
            {
                        System.out.println(“Book Name: ” + this.name);
                        System.out.println(“Book Price: ” + this.price);
            }
            void authorDetails()
            {
                        System.out.println(“Auther Name: ” + this.auther.authorName);
                        System.out.println(“Auther Age: ” + this.auther.age);
                        System.out.println(“Auther place: ” + this.auther.place);
            }
            public static void main(String[] args)
            {
                        Author auther = new Author(“Srinivas”, 33, “INDIA”);
                        Book obj = new Book(“Java-OOPS”, 200, auther);
                        obj.bookDetails();
                        obj.authorDetails();
            }
}
Scroll to Top