Monday, October 28, 2013

Inheritance(IS-A) And Composition(HAS-A)

When you make a complex program which use OOP(Object Oriented Programming) concept you will find many classes that are related with another class.We may have a question why we use many classes.The important key to use many class is we devide a large program into a small program that is related with each other to become a large program.

To know the work way class that is related with another one is to understand two basic concept Inheritance and Composition is very important to understand.So take a look !

Look this Diagram UML about Animal :



Each of these diagrams has a relation.Animal has life(Composition) and Dog is Animal(Inheritance).This is a simple example that is easy to understand.

This is how to change diagram UML to Java program

public class Animal
{
  private Life life; // Animal has
                     // a Composition(HAS-A) with Life
  public Life getLife()
  {
     return life;
  }
}

public class Life 
{
   private String breath;

   public String breathe()
   {
       return breath;
   }
}

public class Dog
       extends Animal // Dog has 
                      // a Inheritance(IS-A) with Animal
{
   private String feather; 

   public String getFeather()
   {
      return feather;
   }

   public void setFeather(String feather)
   {
      this.feather = feather;
   }
}

If you have any question about this subject or example,you can ask here :D

Thanks for reading my blog
Good Luck...

No comments:

Post a Comment