aggregation has a relationship in java

aggregation has a relationship in java
java programming and c, c++, Matlab, Python, HTML, CSS programming language, and new techniques news and any history.

Aggregation (HAS-A)

HAS-A relationship is based on usage, rather than inheritance. In other words, class A has a relationship with class B, if the code in class A has a reference to an instance of class B.
aggregation has a relationship in java free images









Example

class Student
{
 String name;
 Address ad;
}
Here you can say that Student has-a Address.
Here you can say that Student has-a Address.









Student class has an instance variable of type Address. Student code can use Address reference to invoke methods on the Address and get Address behavior.
Aggregation allows you to design classes that follow good Object Oriented practices. It also provides code reusability.

Example of Aggregation

class Author
{
 String authorName;
 int age;
 String place;
 Author(String name,int age,String place)
 {
  this.authorName=name;
  this.age=age;
  this.place=place;
 }
 public String getAuthorName()
 {
  return authorName;
 }
 public int getAge()
 {
  return age;
 }
 public String getPlace()
 {
  return place;
 }
}class Book
{
 String name;
 int price;
 Author auth;
 Book(String n,int p,Author at)
 {
  this.name=n;
  this.price=p;
  this.auth=at;
 }
 public void showDetail()
 {
  System.out.println("Book is"+name);
  System.out.println("price "+price);
  System.out.println("Author is "+auth.getAuthorName());
 }
}

class Test
{
 public static void main(String args[])
 {
  Author ath=new Author("Me",22,"India");
  Book b=new Book("Java",550,ath);
  b.showDetail();
 }
}
Output :
Book is Java.
price is 550.
Author is me.

Q. What is Composition in java?

The composition is a restricted form of Aggregation. For example, a class Car cannot exist without Engine.
class Car
{
 private Engine engine;
 Car(Engine en)
 {
  engine = en;
 }
}

Q. When to use Inheritance and Aggregation?

When you need to use the property and behavior of a class without modifying it in your class. In such a case, Aggregation is a better option. Whereas when you need to use and modify property and behavior of a class inside your class, its best to use Inheritance.









Comments