Saturday, 11 January 2014

Containment and Inheritance


Containment & inheritance are ways of code re-usability. Containment is a 'has-a' relationship while Inheritance is a 'is-a' relationship. Containment means use of object of one class in another while inheritance means reusing the features of a class in its derived class.

Containment:
Containment relationship means the use of an object of a class as a member of another class. Containment is a 'has-a' relation. e.g. an employee 'has-a' joining date.
Example:
class Employee
{
  int emp_id;
  String emp_name;
  MyDate date;   //MyDate is a class having date, month and year

  Emp()
  {
    emp_id=0;
    emp_name="abc";
    date=new MyDate();
  }

  Emp(int id, String name, MyDate d)
  {
    emp_id=id;
    emp_name=name;
    date=d;
  }

public static void main(String args[])
{
  Emp e1=new Emp();
  Emp e2=new Emp(123,"java", new MyDate(23,5,2012));
//to execute this,one needs to write MyDate class
}
}

Inheritance:
Inheritance involves deriving a class from a parent or base class. Inheritance is a 'is-a' relation. e.g.a car 'is-a' vehicle. Inheritance can be used only if one class has ability to behave like other class
Example:
package test;

import date.Date;
public class Employee {
int emp_id,emp_phno,emp_sal;
Date dob;
String name,city;
public Employee(int id,int phno,int sal,String nm,String ct,Date d) {
emp_id = id;
emp_phno = phno;
emp_sal = sal;
name = nm;
city = ct;
dob = d;
}
public void getsal(int sal) {
emp_sal = sal;
}
public String toString() {
return "ID:"+emp_id+"\tName:"+name+"\tContact No:"+emp_phno+"\tCity:"+city+"\tDate of joining:"+dob;
}
public static void main(String[] args) {
Employee emp = new Employee(1, 223323, 30000, "Reshma", "Pune", new Date(1,2,2013));
emp.getsal(30000);
System.out.println(emp+"\tSalary:"+emp.emp_sal);
}
}
----
package test;
import date.Date;
public class Manager extends Employee{

int target, incentives,mgr_sal;
Employee e;
public Manager(int trgt, int inc) {
super(2, 5, 400, "Xyz", "Mnb", new Date(12,3,2012));
target = trgt;
incentives = inc;
mgr_sal = 0;
e = new Employee(2, 332244, 40000, "Shweta", "Mumbai", new Date(12,3,2000));
}
public void getsal(int sal) {
mgr_sal = sal+incentives; 
}
public String toString() {
return e+"\tSalary:"+mgr_sal;
}
public static void main(String[] args) {
Manager mgr = new Manager(100000, 20000);
mgr.getsal(50000);
System.out.println(mgr);
}
}

2 comments: