Thursday 22 March 2018

Association, Aggregation, Composition, Abstraction, Generalization, Realization, Dependency
èWhat is Association?
èWhat is Aggregation?
èWhat is Composition?
èDifference between Aggregation VS Composition?
èInheritance, IS-A and Has-A
èWhat is Abstraction?
èWhat is Generalization?
èWhat is Realization?
èWhat is Dependency?
What is Association?
Association: Association is the relation between two separate classes which establishes through their Objects. In other words, Association defines the multiplicity between objects. Association can be one-to-one, one-to-many, many-to-one, many-to-many.
                
èAggregation is a special form of Association.
èComposition is a special form of Aggregation.
èIt is unidirectional .
 

Example: A Student and a Faculty are having an association.
Example With Java Code:
// Java program to illustrate the
// concept of Association
import java.io.*;

// class bank
class Bank {
     private String name;

     // bank name
     Bank(String name) {
          this.name = name;
     }

     public String getBankName() {
          return this.name;
     }
}

// employee class
class Employee {
     private String name;

     // employee name
     Employee(String name) {
          this.name = name;
     }

     public String getEmployeeName() {
          return this.name;
     }
}

// Association between both the
// classes in main method
class Association {
     public static void main(String[] args) {
          Bank bank = new Bank("Axis");
          Employee emp = new Employee("Sitansu");

System.out.println(emp.getEmployeeName() + " is employee of " + bank.getBankName());
     }
}

Output:
Sitansu is employee of Axis
Bank and employee are associated through their Objects. Bank Can have Many Employee (One to Many Relationship)

èWhat is Aggregation?
Aggregation: It is a special form of Association where:
·        It represents Has-A relationship.
·        It is a unidirectional association i.e. a one-way relationship. For example, the department can have students but vice versa is not possible and thus unidirectional in nature.
·        In Aggregation, both the entries can survive individually which means ending one entity will not affect the other entity

Example:

// Java program to illustrate
// the concept of Aggregation.
import java.io.*;
import java.util.*;

// student class
class Student {
     String name;
     int id;
     String dept;

     Student(String name, int id, String dept) {

          this.name = name;
          this.id = id;
          this.dept = dept;

     }
}

/*
 * Department class contains list of student Objects. It is associated with
 * student class through its Object(s).
 */
class Department {

     String name;
     private List<Student> students;

     Department(String name, List<Student> students) {

          this.name = name;
          this.students = students;

     }

     public List<Student> getStudents() {
          return students;
     }
}

/*
 * Institute class contains list of Department Objects. It is asoociated with
 * Department class through its Object(s).
 */
class Institute {

     String instituteName;
     private List<Department> departments;

     Institute(String instituteName, List<Department> departments) {
          this.instituteName = instituteName;
          this.departments = departments;
     }

     // count total students of all departments
     // in a given institute
     public int getTotalStudentsInInstitute() {
          int noOfStudents = 0;
          List<Student> students;
          for (Department dept : departments) {
              students = dept.getStudents();
              for (Student s : students) {
                   noOfStudents++;
              }
          }
          return noOfStudents;
     }

}

// main method
class GFG {
     public static void main(String[] args) {
          Student s1 = new Student("Sitansu", 1, "CSE");
          Student s2 = new Student("Kuldeep", 2, "CSE");
          Student s3 = new Student("Bimal", 1, "EE");
          Student s4 = new Student("Goutham", 2, "EE");

          // making a List of
          // CSE Students.
          List<Student> cse_students = new ArrayList<Student>();
          cse_students.add(s1);
          cse_students.add(s2);

          // making a List of
          // EE Students
          List<Student> ee_students = new ArrayList<Student>();
          ee_students.add(s3);
          ee_students.add(s4);

          Department CSE = new Department("CSE", cse_students);
          Department EE = new Department("EE", ee_students);

          List<Department> departments = new ArrayList<Department>();
          departments.add(CSE);
          departments.add(EE);

          // creating an instance of Institute.
          Institute institute = new Institute("BITS", departments);

          System.out.print("Total students in institute: ");
          System.out.print(institute.getTotalStudentsInInstitute());
     }
}

Output:
Total students in institute: 4
In this example, there is an Institute which has no. of departments like CSE, EE. Every department has no. of students. So, we make a Institute class which has a reference to Object or no. of Objects (i.e. List of Objects) of the Department class. That means Institute class is associated with Department class through its Object(s). And Department class has also a reference to Object or Objects (i.e. List of Objects) of Student class means it is associated with Student class through its Object(s).
When do we use Aggregation?
Code reuse is best achieved by aggregation.


What is Composition?
Composition: Composition is a restricted form of Aggregation in which two entities are highly dependent on each other.
§  It represents the part-of relationship.
§  In composition, both the entities are dependent on each other.
§  When there is a composition between two entities, the composed object cannot exist without the other entity.

Let's take the example of Library.

/*
 * Department class contains list of student Objects. It is associated with
 * student class through its Object(s).
 */
class Department {

     String name;
     private List<Student> students;

     Department(String name, List<Student> students) {

          this.name = name;
          this.students = students;

     }

     public List<Student> getStudents() {
          return students;
     }
}

/*
 * Institute class contains list of Department Objects. It is asoociated with
 * Department class through its Object(s).
 */
class Institute {

     String instituteName;
     private List<Department> departments;

     Institute(String instituteName, List<Department> departments) {
          this.instituteName = instituteName;
          this.departments = departments;
     }

     // count total students of all departments
     // in a given institute
     public int getTotalStudentsInInstitute() {
          int noOfStudents = 0;
          List<Student> students;
          for (Department dept : departments) {
              students = dept.getStudents();
              for (Student s : students) {
                   noOfStudents++;
              }
          }
          return noOfStudents;
     }

}

// main method
class GFG {
     public static void main(String[] args) {
          Student s1 = new Student("Mia", 1, "CSE");
          Student s2 = new Student("Priya", 2, "CSE");
          Student s3 = new Student("John", 1, "EE");
          Student s4 = new Student("Rahul", 2, "EE");

          // making a List of
          // CSE Students.
          List<Student> cse_students = new ArrayList<Student>();
          cse_students.add(s1);
          cse_students.add(s2);

          // making a List of
          // EE Students
          List<Student> ee_students = new ArrayList<Student>();
          ee_students.add(s3);
          ee_students.add(s4);

          Department CSE = new Department("CSE", cse_students);
          Department EE = new Department("EE", ee_students);

          List<Department> departments = new ArrayList<Department>();
          departments.add(CSE);
          departments.add(EE);

          // creating an instance of Institute.
          Institute institute = new Institute("BITS", departments);

          System.out.print("Total students in institute: ");
          System.out.print(institute.getTotalStudentsInInstitute());
     }
}
Output
Title : EffectiveJ Java and  Author : Joshua Bloch
Title : Thinking in Java and  Author : Bruce Eckel
Title : Java: The Complete Reference and  Author : Herbert Schildt
So, If Library gets destroyed then All books within that particular library will be destroyed. i.e. book can not exist without library. That’s why it is composition.





Difference between Aggregation VS Composition ?

Aggregation VS Composition
1.     Dependency: Aggregation implies a relationship where the child can exist independently of the parent. For example, Bank and Employee, delete the Bank and the Employee still exist. whereas Composition implies a relationship where the child cannot exist independent of the parent. Example: Human and heart, heart don’t exist separate to a Human
2.     Type of Relationship: Aggregation relation is “has-a” and composition is “part of” relation.
3.     Type of association: Composition is a strong Association whereas Aggregation is a weak association.

Example:

// Java program to illustrate the
// difference between Aggregation
// Composition.

import java.io.*;

// Engine class which will
// be used by car. so 'Car'
// class will have a field
// of Engine type.
class Engine {
     // starting an engine.
     public void work() {

          System.out.println("Engine of car has been started ");

     }

}

// Engine class
final class Car {

     // For a car to move,
     // it need to have a engine.
     private final Engine engine; // Composition
     // private Engine engine; // Aggregation

     Car(Engine engine) {
          this.engine = engine;
     }

     // car start moving by starting engine
     public void move() {

          // if(engine != null)
          {
              engine.work();
              System.out.println("Car is moving ");
          }
     }
}

class GFG {
     public static void main(String[] args) {

          // making an engine by creating
          // an instance of Engine class.
          Engine engine = new Engine();

          // Making a car with engine.
          // so we are passing a engine
          // instance as an argument while
          // creating instace of Car.
          Car car = new Car(engine);
          car.move();

     }
}


Output:
Engine of car has been started 
Car is moving 


In case of aggregation, the Car also performs its functions through an Engine. but the Engine is not always an internal part of the Car. An engine can be swapped out or even can be removed from the car. That’ why we make The Engine type field non-final.

What is Generalization?
Inheritance/ Generalization, IS-A and Has-A: Depends on the logical relation. It just needs to make sense.
Example:
Lets say you have Animal classes.
So you have these classes: Animal, Dog, Cat , Leopard, Fur, Feet
Cat and Dog IS A Animal.
Leopard IS A Cat.
Animal HAS A Fur, Feet.
In a nutshell:
IS A relationship means you inherit and extend the functionality of the base class.
HAS A relationship means the class is using another class, so it has it as a member.

An IS-A relationship is inheritances. The classes which inherit are known as sub classes or child classes. On the other hand, HAS - A relationship is a composition
In OOP, IS - A relationship is completely inheritance. This means, that the child class is a type of parent class. For example, an apple is a fruit. So you will extend fruit to get the apple.
class Apple extends Fruit{
.
.
}
On the other hand, composition means creating instances which have references to other objects. For example, a room has a table. So you will create a class room and then in that class create an instance of type table.

class Room{

:
Table table = new Table ();
:
:
}

A HAS-A relationship is dynamic (run time ) binding while inheritance is a static (compile time ) binding. If you just want to reuse the code and you know that the two are not of same kind use composition. For example, you cannot an oven from a kitchen. A kitchen HAS-A oven. When you feel there is a natural relationship like Apple is a Fruit use inheritance.

What is Abstraction?
Abstraction: Data Abstraction is the property by virtue of which only the essential details are displayed to the user.The trivial or the non-essentials units are not displayed to the user. Ex: A car is viewed as a car rather than its individual components.
Data Abstraction may also be defined as the process of identifying only the required characteristics of an object ignoring the irrelevant details.The properties and behaviors of an object differentiate it from other objects of similar type and also help in classifying/grouping the objects.
Consider a real-life example of a man driving a car. The man only knows that pressing the accelerators will increase the speed of car or applying brakes will stop the car but he does not know about how on pressing the accelerator the speed is actually increasing, he does not know about the inner mechanism of the car or the implementation of accelerator, brakes etc in the car. This is what abstraction is.

In java, abstraction is achieved by Interface and abstract class. We can achieve 100% abstraction using interfaces.
Abstract classes and Abstract methods :
1.     An abstract class is a class that is declared with abstract keyword.
2.     An abstract method is a method that is declared without an implementation.
3.     An abstract class may or may not have all abstract methods. Some of them can be concrete methods
4.     A method defined abstract must always be redefined in the subclass,thus making overridingcompulsory OR either make subclass itself abstract.
5.     Any class that contains one or more abstract methods must also be declared with abstract keyword.
6.     There can be no object of an abstract class.That is, an abstract class can not be directly instantiated with the new operator.
7.     An abstract class can have parametrized constructors and default constructor is always present in an abstract class.



When to use abstract classes and abstract methods with an example

There are situations in which we will want to define a superclass that declares the structure of a given abstraction without providing a complete implementation of every method. That is, sometimes we will want to create a superclass that only defines a generalization form that will be shared by all of its subclasses, leaving it to each subclass to fill in the details.
Consider a classic “shape” example, perhaps used in a computer-aided design system or game simulation. The base type is “shape” and each shape has a color, size and so on. From this, specific types of shapes are derived(inherited)-circle, square, triangle and so on – each of which may have additional characteristics and behaviors. For example, certain shapes can be flipped. Some behaviors may be different, such as when you want to calculate the area of a shape. The type hierarchy embodies both the similarities and differences between the shapes.


// Java program to illustrate the
// concept of Abstraction
abstract class Shape {
     String color;

     // these are abstract methods
     abstract double area();

     public abstract String toString();

     // abstract class can have constructor
     public Shape(String color) {
           System.out.println("Shape constructor called");
           this.color = color;
     }

     // this is a concrete method
     public String getColor() {
           return color;
     }
}

class Circle extends Shape {
     double radius;

     public Circle(String color, double radius) {

           // calling Shape constructor
           super(color);
           System.out.println("Circle constructor called");
           this.radius = radius;
     }

     @Override
     double area() {
           return Math.PI * Math.pow(radius, 2);
     }

     @Override
     public String toString() {
           return "Circle color is " + super.color + "and area is : " + area();
     }

}

class Rectangle extends Shape {

     double length;
     double width;

     public Rectangle(String color, double length, double width) {
           // calling Shape constructor
           super(color);
           System.out.println("Rectangle constructor called");
           this.length = length;
           this.width = width;
     }

     @Override
     double area() {
           return length * width;
     }

     @Override
     public String toString() {
           return "Rectangle color is " + super.color + "and area is : " + area();
     }

}

public class Test {
     public static void main(String[] args) {
           Shape s1 = new Circle("Red", 2.2);
           Shape s2 = new Rectangle("Yellow", 2, 4);

           System.out.println(s1.toString());
           System.out.println(s2.toString());
     }
}

Output:
Shape constructor called
Circle constructor called
Shape constructor called
Rectangle constructor called
Circle color is Redand area is : 15.205308443374602
Rectangle color is Yellowand area is : 8.0

Advantages of Abstraction

1.     It reduces the complexity of viewing the things.
2.     Avoids code duplication and increases reusability.
3.     Helps to increase security of an application or program as only important details are provided to the user.

What is Realization?
Realization: Realization is a relationship between the blueprint class and the object containing its respective implementation level details. This object is said to realize the blueprint class. In other words, you can understand this as the relationship between the interface and the implementing class.

Example: A particular model of a car ‘GTB Fiorano’ that implements the blueprint of a car realizes the abstraction.


public interface MyRunnable {

}

public class RunnableTask implements MyRunnable {

}

What is Dependency?

Dependency: Change in structure or behavior of a class affects the other related class, then there is a dependency between those two classes. It need not be the same vice-versa. When one class contains the other class it this happens.


Example: Relationship between shape and circle is the dependency.