Thursday 26 June 2014

Association Vs Aggregation Vs Composition

Association

It represents a relationship between two or more objects where all objects have their own lifecycle and there is no owner. The name of an association specifies the nature of relationship between objects. This is represented by a solid line.
Let’s take an example of relationship between Professor and Book. Multiple Professor can associate with a single Book and a single Professor can associate with multiple Book. But there is no ownership between the objects and both have their own lifecycle. Both can be created and deleted independently.

Professor playing the role of author associated with textbook end typed as Book.
Professor playing the role of author associated with textbook end typed as Book.


Aggregation

It is a specialized form of Association where all object have their own lifecycle but there is ownership. This represents “whole-part or a-part-of” relationship. This is represented by a hollow diamond followed by a line.
Let’s take an example of relationship between Department(Container) and Teacher(Contained). A Teacher may belongs to multiple departments. Hence Teacher is a part of multiple departments. But if we destroy a Department(Container Object), Teacher Object(Contained Object ) will not destroy. Objects are not dependent.

                    
         HAS A Relation ->   Department HAS A Teacher


An aggregation is used when life of object is independent of container object But still container object owns the aggregated object.

Example :  Suppose Organization has Person as employees, relationship between them is Aggregation. Here is how they look like in terms of Java classes

public class Organization {
    private List employees;
}

public class Person {
    private String name;   
}


Other Eg: Team has players, If team dissolve, Player will still exists.


Composition

It is a specialized form of Aggregation. It is a strong type of Aggregation. In this relationship child objects does not have their lifecycle without Parent object. If a parent object is deleted, all its child objects will also be deleted. This represents “death” relationship. This is represented by a solid diamond followed by a line.
Let’s take an example of relationship between House(Container) and rooms(Contained). House can contain multiple rooms there is no independent life of room and any room cannot belongs to two different house if we destroy  the house(Container Object)  then room(Contained Object) will be  automatically destroyed.
Objects are dependent.

       HAS A Relation ->  House HAS A Room


A composition is used where each part may belong to only one whole at a time.



Other Example  : Since Engine is 
part-of Car, relationship between them is Composition. Here is how they are implemented between Java classes.If we destroy the Car then engine will be destroyed. 

public class Car {
    //final will make sure engine is initialized
    private final Engine engine;  
       
    public Car(){
       engine  = new Engine();
    }
}

class Engine {
    private String type;
}


UML Diagram of Association, Composition and Aggregation 

UML has different notations to denote aggregation, composition and association.  Association is denoted by simple arrow, while aggregation is denoted by  empty diamond head arrow and composition is denoted by filled diamond head arrow. When you draw UML diagram for two related class A and B, where A is associated with B then its denoted by A -> B. Similar way is used to show aggregation and composition between two classes. Here is UML notations for different kind of dependency between two classes.

Difference between Association, Aggregation and Composition


As, I said all three denotes relationship between object and only differ in their strength, you can also view them as below, where composition represent strongest form of relationship and association being the most general form.

Association vs Aggregation vs Composition



Association vs Composition vs Aggregation

Here is the list of differences between Composition and Aggregation in point format, for quick review. As I said key difference between them comes from the point that in case of Composition, One object is OWNER of other object, while in case of aggregation, one object is just a USER or another object.

1) If A and B two classes are related to each other such that, B ceased to exist, when A is destroyed, then association between two object is known as Composition. Example is Car and Engine. While if A and B are associated with each other, such that B can exist without being associated with A, then this association in known as Aggregation.

2) In case of Composition A owns B e.g. Person is owner of his HandMind and Heart, while  in case of Aggregation, A uses B e.g. Organization uses People as employee.

3) In UML diagram Association is denoted by normal arrow head, while Composition is represented by filled diamond arrow head, and Aggregation is represented by empty diamond arrow head, As shown in below and attached diagram in third paragraph.

Association  A---->B
Composition  A-----<filled>B
Aggregation  A-----<>B

4) Aggregation is a lighter form of Composition, where sub-part object can meaningfully exits without main objects.

5) In Java, you can use final keyword to represent Composition. Since in Composition, Owner object expect part object to be available and functions, by making it final, your provide guarantee that, when Owner will be created, this part object will exist. This is actually a Java idiom to represent strong form of association i.e. composition between two objects.

6) Another interesting word, which comes handy to understand difference between Composition and Aggregation in software design is "part-of" and "has". If one object is part-of another object e.g. Engine is part of Car, then association or relationship between them is Composition. On the other hand if one object just has another object e.g. Car has driver than it's Aggregation.





Wednesday 25 June 2014

What’s a virtual destructor In C++, and when is it needed?

As you may know, in C++ a destructor is generally used to deallocate memory and do some other cleanup for a class object and it’s class members whenever an object is destroyed. Destructors are distinguished by the tilde, the ‘~’ that appears in front of the destructor name. In order to define a virtual destructor, all you have to do is simply add the keyword “virtual” before the tilde symbol.
The need for virtual destructors in C++ is best illustrated by some examples. Let’s start by going through an example that does not use virtual destructors, and then we will go through an example that does use virtual destructors. Once you see the difference, you will understand why virtual destructors are needed. Take a look at the code below to start out:

Example without a Virtual Destructor:
#include iostream.h
class Base
{
    public:
       Base(){ cout<<"Constructing Base";}
       
     // this is a destructor:
 
 ~Base(){ cout<<"Destroying Base";}
};

class Derive: public Base
{
        public:
        Derive(){ cout<<"Constructing Derive";}
        
        ~Derive(){ cout<<"Destroying Derive";}
 };

void main()
{
     Base *basePtr = new Derive();
        
        delete basePtr;
}
The output after running the code above would be:
Constructing Base  
Constructing Derive 
Destroying Base

Based on the output above, we can see that the constructors get called in the appropriate order when we create the Derive class object pointer in the main function.
But there is a major problem with the code above: the destructor for the "Derive" class does not get called at all when we delete ‘basePtr’.
So, how can we fix this problem?
Well, what we can do is make the base class destructor virtual, and that will ensure that the destructor for any class that derives from Base (in our case, its the "Derive" class) will be called.

Example with a Virtual Destructor:

So, the only thing we will need to change is the destructor in the Base class and here’s what it will look like – note that we highlighted the part of the code where the virtual keyword has been added in red:
class Base
{
    public:
       Base(){ cout<<"Constructing Base";}

 // this is a virtual destructor:
 virtual ~Base(){ cout<<"Destroying Base";}
};
Now, with that change, the output after running the code above will be:
Constructing Base  
Constructing Derive 
Destroying Derive
Destroying Base
Note that the derived class destructor will be called before the base class.
So, now you’ve seen why we need virtual destructors and also how they work.

Difference between method Overloading and Overriding in java

Here we will discuss the difference between overloading and overriding in Java. If you are new to these terms then refer the following posts:
  1. Method overloading in java
  2. Method overriding in java

Overloading vs Overriding in Java

  1. Overloading happens at compile-time while Overriding happens at runtime: The binding of overloaded method call to its definition has happens at compile-time however binding of overridden method call to its definition happens at runtime.
  2. Static methods can be overloaded which means a class can have more than one static method of same name. Static methods cannot be overridden, even if you declare a same static method in child class it has nothing to do with the same method of parent class.
  3. The most basic difference is that overloading is being done in the same class while for overriding base and child classes are required. Overriding is all about giving a specific implementation to the inherited method of parent class.
  4. Static binding is being used for overloaded methods and dynamic binding is being used for overridden/overriding methods.
  5. Performance: Overloading gives better performance compared to overriding. The reason is that the binding of overridden methods is being done at runtime.
  6. private and final methods can be overloaded but they cannot be overridden. It means a class can have more than one private/final methods of same name but a child class cannot override the private/final methods of their base class.
  7. Return type of overloaded method should be same as the other methods of the same name however return type of overriding method can be different from overridden method.
  8. Argument list should be different while doing method overloading. Argument list should be same in method Overriding.

Overloading example


class Sum
{
    int add(int n1, int n2) 
    {
        return n1+n2;
    }
    int add(int n1, int n2, int n3) 
    {
        return n1+n2+n3;
    }
    int add(int n1, int n2, int n3, int n4) 
    {
        return n1+n2+n3+n4;
    }
    int add(int n1, int n2, int n3, int n4, int n5) 
    {
        return n1+n2+n3+n4+n5;
    }
    public static void main(String args[])
    {
     Sum obj = new Sum();
     System.out.println("Sum of two numbers: "+obj.add(20, 21));
     System.out.println("Sum of three numbers: "+obj.add(20, 21, 22));
     System.out.println("Sum of four numbers: "+obj.add(20, 21, 22, 23));
     System.out.println("Sum of five numbers: "+obj.add(20, 21, 22, 23, 24));
    }
}
Output:
Sum of two numbers: 41
Sum of three numbers: 63
Sum of four numbers: 86
Sum of five numbers: 110
Here we have 4 versions of same method add. We are overloading the methodadd() here.

Overriding example


class CarClass
{
    public int speedLimit() 
    {
        return 100;
    }
}
class Ford extends CarClass
{
    public int speedLimit()
    {
        return 150;
    }
    public static void main(String args[])
    {
     CarClass obj = new Ford();
     int num= obj.speedLimit();
     System.out.println("Speed Limit is: "+num);
    }
}
Output:
Speed Limit is: 150
Here speedLimit() method of class Ford is overriding the speedLimit()method of class CarClass.

Static and dynamic binding in java

Before explain static and dynamic binding in java, lets discuss few terms which will help you to understand the concepts better.

What is reference and object?

class Human{
....
}
class Boy extends Human{
   public static void main( String args[]) {
       /*This statement simply creates an object of class
        *Boy and assigns a reference of Boy to it*/  
       Boy obj1 = new Boy();

       /* Since Boy extends Human class. The object creation
        * can be done in this way. Parent class reference 
        * can point to a child class object*/
       Human obj2 = new Boy();
   }
}

Static and Dynamic Binding in Java

Association of method definition to the method call is known as binding. There are two types of binding: Static binding and dynamic binding. Lets discuss them one by one.

Static Binding or Early Binding

The binding which can be resolved at compile time by compiler is known as static or early binding. All the static, private and final methods have always been bonded at compile-time . Why Static, final and private methods binding is always a static binding? You would understand it better after reading dynamic binding. Still let me explain this – Compiler knows that all such methods cannot be overloaded and will always be accessed by object of local class. Hence compiler doesn’t have any difficulty to determine object of class (local class for sure). That’s the reason binding for such methods are static.

Static binding example

class Human{
....
}
class Boy extends Human{
   public void walk(){
      System.out.println("Boy walks");
   }
   public static void main( String args[]) {
      Boy obj1 = new Boy();
      obj1.walk();
   }
}
Here we have created an object of Boy class and calling the method walk() of the same class. Since nothing is ambiguous here, compiler would be able to resolve this binding during compile-time, such kind of binding is known as static binding.

Dynamic Binding or Late Binding

When compiler is not able to resolve the call/binding at compile time, such binding is known as Dynamic or late Binding. Overriding is a perfect example of dynamic binding as in overriding both parent and child classes have same method. Thus while calling the overridden method, the compiler gets confused between parent and child class method(since both the methods have same name).

Dynamic binding example

Here Human is a super class and Boy is a child class since Boy extends Human. Both these classes have a same method void walk(). Since we have assigned the parent class reference to the child class object, during call of walk() method the compiler would not be able to decide which walk() method to call. It will be confused between the walk() method of Human class and walk() method of Boy class. Such kind of bindings are known as dynamic binding as compiler figures out the object type in runtime.

class Human{
   public void walk()
   {
       System.out.println("Human walks");
   }
}
class Boy extends Human{
   public void walk(){
       System.out.println("Boy walks");
   }
   public static void main( String args[]) {
       //Reference is of parent class
       Human myobj = new Boy();
       myobj.walk();
   }
}
Output:
Boy walks

Static Binding vs Dynamic Binding

Lets discuss the difference between static and dynamic binding in Java.
  1. Static binding happens at compile-time while dynamic binding happens at runtime.
  2. Binding of private, static and final methods always happen at compile time since these methods cannot be overridden. Binding of overridden methods happen at runtime.
  3. Java uses static binding for overloaded methods and dynamic binding for overridden methods.

Polymorphism in Java – Method Overloading and Overriding

Here we will discuss polymorphism, which is one of the feature of Object oriented programming(OOPs).

What is polymorphism in programming?

Polymorphism is the capability of a method to do different things based on the object that it is acting upon. In other words, polymorphism allows you define one interface and have multiple implementations. I know it sounds confusing. Don’t worry we will discuss this in detail.
  • It is a  feature that allows one interface to be used for a general class of  actions.
  • An operation may exhibit different behavior in different instances.
  • The behavior depends on the types of data used in the operation.
  • It plays an important role in allowing objects having different internal structures to share the same external interface.
  • Polymorphism is extensively used in implementing inheritance.
Following concepts demonstrate different types of polymorphism in java.
 1->Method Overloading
2->Method Overriding
Method Definition:
A method is a set of code which is referred to by name and can be called (invoked) at any point in a program simply by utilizing the method’s name.
1)Method Overloading:
In Java, it is possible to define two or more methods of same name in a class, provided that there argument list or parameters are different. This concept is known as Method Overloading.
I have covered method overloading and Overriding below. 

1) Method Overloading

  1. To call an overloaded method in Java, it is must to use the type and/or number of arguments to determine which version of the overloaded method to actually call.
  2. Overloaded methods may have different return types; the return type alone is insufficient to distinguish two versions of a method. .
  3. When Java encounters a call to an overloaded method, it simply executes the version of the method whose parameters match the arguments used in the call.
  4. It allows the user to achieve compile time polymorphism.
  5. An overloaded method can throw different exceptions.
  6. It can have different access modifiers.
Example:
class Overload
{
    void demo (int a)
    {
       System.out.println ("a: " + a);
    }
    void demo (int a, int b)
    {
       System.out.println ("a and b: " + a + "," + b);
    }
    double demo(double a) {
       System.out.println("double a: " + a);
       return a*a;
    }
}
class MethodOverloading
{
    public static void main (String args [])
    {
        Overload Obj = new Overload();
        double result;
        Obj .demo(10);
        Obj .demo(10, 20);
        result = Obj .demo(5.5);
        System.out.println("O/P : " + result);
    }
}
Here the method demo() is overloaded 3 times: first having 1 int parameter, second one has 2 int parameters and third one is having double arg. The methods are invoked or called with the same type and number of parameters used.
Output:
a: 10
a and b: 10,20
double a: 5.5
O/P : 30.25
Rules for Method Overloading
  1. Overloading can take place in the same or in its sub-class.
  2. Constructor in Java can be overloaded
  3. Overloaded methods must have a different argument list.
  4. Overloaded method should always be in part of the same class, with same name but different parameters.
  5. The parameters may differ in their type or number, or in both.
  6. They may have the same or different return types.
  7. It is also known as compile time polymorphism.

2) Method Overriding

Child class has the same method as of base class. In such cases child class overrides the parent class method without even touching the source code of the base class. This feature is known as method overriding.
Example:
public class BaseClass
{
    public void methodToOverride() //Base class method
    {
         System.out.println ("I'm the method of BaseClass");
    }
}
public class DerivedClass extends BaseClass
{
    public void methodToOverride() //Derived Class method
    {
         System.out.println ("I'm the method of DerivedClass");
    }
}

public class TestMethod
{
     public static void main (String args []) {
        // BaseClass reference and object
        BaseClass obj1 = new BaseClass(); 
        // BaseClass reference but DerivedClass object
        BaseClass obj2 = new DerivedClass(); 
        // Calls the method from BaseClass class
        obj1.methodToOverride(); 
        //Calls the method from DerivedClass class
        obj2.methodToOverride(); 
     }
}
Output:
I'm the method of BaseClass
I'm the method of DerivedClass
Rules for Method Overriding:
  1. applies only to inherited methods
  2. object type (NOT reference variable type) determines which overridden method will be used at runtime
  3. Overriding methods must have the same return type
  4. Overriding method must not have more restrictive access modifier
  5. Abstract methods must be overridden
  6. Static and final methods cannot be overridden
  7. Constructors cannot be overridden
  8. It is also known as Runtime polymorphism.

super keyword in Overriding:

When invoking a superclass version of an overridden method the super keyword is used.
Example:
class Vehicle {
    public void move () {
         System.out.println ("Vehicles are used for moving from one place to another ");
    }
}

class Car extends Vehicle {
    public void move () {
      super. move (); // invokes the super class method
      System.out.println ("Car is a good medium of transport ");
    }
}

public class TestCar {
    public static void main (String args []){
        Vehicle b = new Car (); // Vehicle reference but Car object
        b.move (); //Calls the method in Car class
    }
}
Output:
Vehicles are used for moving from one place to another
Car is a good medium of transport