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.

59 comments:

  1. Very useful information. You can get more data science details at http://www.onefederalsolution.com/our-services/data-science/

    ReplyDelete
  2. Nice Post. I like your blog. Thanks for Sharing.
    Java Training in Noida

    ReplyDelete
  3. Nice article . you have explain step by step Java file examples

    ReplyDelete
  4. https://javarevisited.blogspot.com/2017/02/how-to-consume-json-from-restful-web-services-Spring-RESTTemplate-Example.html#comment-form

    ReplyDelete
  5. This comment has been removed by the author.

    ReplyDelete
  6. We're here to present one into this Android Assignment Help and Android Profession project development help providers.

    ReplyDelete
  7. Good Post! Thank you so much for sharing this pretty post, it was so good to read and useful to improve my knowledge as an updated one, keep blogging…
    Oracle Java Certifications

    ReplyDelete
  8. Very Useful information about Interview Question. It will help me a lot. But Can we say Primitive Data Types in Java as Reference Data Type?

    ReplyDelete
  9. I love the way the trainer has demonstrated. I have no prior knowledge about Digital marketing but still i can understand the concepts better. Thanks to Team Brolly for this awesome video course!

    ReplyDelete
  10. This comment has been removed by the author.

    ReplyDelete
  11. Thank you for sharing this amazing post. Looking forward to reading more.
    Visit us: Java Training
    Visit us: Java Course

    ReplyDelete
  12. One of the best blog spot I have ever seen. Reading this blog is make a curiosity to learn Programming. Keep up the good work.
    Core Java Training in Bangalore | Python Training in Bangalore | AWS Training in Bangalore

    ReplyDelete
  13. This post is so interactive and informative.keep updating more information...
    Java Course Duration
    Future Of Java Developer

    ReplyDelete
  14. Great Post. Very informative. Keep Sharing!!

    Apply Now JAVA Training in Noida
    For more details about the course fee, duration, classes, certification, and placement call our expert at 70-70-90-50-90

    ReplyDelete
    Replies
    1. Very Informative and creative contents. This concept is a good way to enhance the knowledge. thanks for sharing. Continue to share your knowledge through articles like these, and keep posting more blogs. And more Information Data Labeling Service for Machine LearningVery Informative and creative contents. This concept is a good way to enhance the knowledge. thanks for sharing. Continue to share your knowledge through articles like these, and keep posting more blogs. And more Information Data Labeling Service for Machine Learning

      Delete
  15. Thanks for Sharing This Article. Assignment Writing Service is a website that allows you to Online Assignment Help online. Easily to write, Assignment Help Online with trained male and female teachers in Online Classes For Indian Students..

    ReplyDelete
  16. The global flexible foam market is expected to grow from USD 35.86 billion in 2016 to USD 64.14 billion by 2026, at a CAGR of 5.99% from 2016 to 2026. Flexible foams are used as cushioning material in the different end use products such as beds, mattresses, chairs, garden furniture pillows, carpet cushions, automobile parts (seats, arm rest, headrests, and others), and others. Flexible Foam consist of different types of foam which are used for cushioning purpose. It is a type of polymeric foam produce by combination of TDI, polyols, additives, and blowing agents.

    ReplyDelete
  17. nice post.. I am looking for content writer companies dubai for my assignments and also help me for the content of my websites.

    ReplyDelete
  18. Dicsinnovatives in Delhi is one of the most reputed institution offering specialized digital marketing course in pitampura, Delhi. with 100% Placement ; Digital marketing institute in pitampura, Join now dicsinnovatives EMI Available. Enroll Now. Training.100+ Hiring Partners. Expert-Led Online Course. Industry Expert Faculty

    ReplyDelete
  19. Tax benefits hiring family Members to Work for Your Business Family-owned businesses have been around for generations. When you own your own business, it is important to understand how your tax situation will change and what actions can be taken to reduce your tax liability legally.
    minimum fixed deposit 
    understanding listed options 
    people investment long 
    fit culture add 
    home decor accessories 
    real meaning holidays 
    adventure travel actually 
    learning style fashion 

    ReplyDelete
  20. I am really very happy to visit your blog. Directly I am found which I truly need. please visit our website for more information about AI technology for healthcare business

    ReplyDelete
  21. The best cheapest logo design service is here providing best services. At Logo Design Service, we allow you to shine with a custom identity. No matter if you’re about to start your business or already a well-established company, our logo designers Dubai know how to revamp the design or create a new one.

    ReplyDelete
  22. I really appreciate your blog, it is really helpful for all. Keep blogging to attract reader's attention

    Visit our website for smart lights, motion sensors, home automation devices. We are leading smart home lighting providers in Vadodara


    ReplyDelete
  23. I like Your articles and your information is so clear. I appreciate your work
    Visit our website for best student visa & immigration consultation services in Vadodara, Contact us for Study Abroad Consultants in Vadodara

    ReplyDelete
  24. Great blog. Thank you for sharing information

    Visit our store for Buy Apple Products Online. iMagic Baroda is the leading Apple iPhone Showroom in Vadodara

    ReplyDelete

  25. I am really very happy to visit your blog. Directly I am found which I truly need. please visit our website for more information
    Data visualization Service in USA

    ReplyDelete
  26. Nice post. visit my site i am logo designer at Logo maker Abu Dhabi

    ReplyDelete
  27. It's a very helpful article for an a Preparing for Java Developer. Discovered a source to get more information about best java coaching in lucknow

    ReplyDelete

  28. Very Informative and creative contents. This concept is a good way to enhance the knowledge. thanks for sharing.
    Continue to share your knowledge through articles like these, and keep posting more blogs.
    And more Information JavaScript Development Services

    ReplyDelete
  29. "By signing in to Database assignment help you save a ton of time and also save the limited monetary resources that a student has.
    Our services are very reasonably priced considering the limitations of our student friends."

    ReplyDelete
  30. Join Now Java course , Online Java course
    https://corosocial.com/read-blog/141413_future-of-java-technology-will-help-you-get-there.html
    APTRON provides the best Java course , Online Java course for beginners as well as advanced programmers. Java course, Online Java course will help you to learn and nourish your programming skills in Java.

    ReplyDelete
  31. Great. Have you heard about our cheap assignment help UAE writers keep on doing this everyday act will let you get your degree soon.

    ReplyDelete
  32. Assignment Help
    Assignment help and with writing assignments. Experts at thetutorshelp.com will help you solve all your homework assignments and other student assignments. We provide live Homework help, Assignment Help, Online Tutoring and Test Preparation Services.Seemore- https://www.thetutorshelp.com/assignment-help.php
    Assignment Help

    ReplyDelete
  33. Great to know about neverfull louis vuitton best handbags for women!

    ReplyDelete
  34. Do you need Marketing Assignment Help in UAE? Do not worry we are here to help you choose Assignment Help AUS. Our Experts ability of quality research and writing on short deadline. Our Assignment Help UAE is affordable and unique. We are available is 24*7for every students. Visit us!

    ReplyDelete
  35. Great blog The content is informative and engaging. The author's writing style is captivating. Visit my website to get best Information About HR Generalist Training in Noida and mention Below Technologies.

    HR Generalist Training in Noida

    ReplyDelete
  36. informative blog , keep posting and dont forget to checkout our blog java classes in satara

    ReplyDelete
  37. Thanks for this post . Keep sharing
    Java Course in Solapur

    ReplyDelete
  38. infomative blog, keep posting . If you want to learn about java web developer then checkout java course in pune

    ReplyDelete

  39. Thank you for sharing this valuable content. I genuinely appreciate well-crafted and insightful information like this. The ideas presented here are not only excellent but also incredibly engaging, which enhances the overall reading experience. Keep up the fantastic work, and I look forward to more of your contributions.
    visit: Data Cleaning and Preprocessing: Ensuring Data Quality

    ReplyDelete
  40. Great article. Funded Account Forex opportunities are a fantastic way for traders to showcase their skills without risking personal capital. They allow both new and experienced traders to access significant trading funds while focusing on strategy and disciplined execution. It's exciting to see how these setups encourage responsible risk management and offer real rewards for consistent performance. The ability to trade larger amounts while sharing profits is a game-changer for anyone serious about forex trading. Understanding the rules and maintaining discipline are key to achieving long-term success in this dynamic market. Visit us for more information.

    ReplyDelete