Sunday, April 3, 2011

Difference IS-A and HAS-A Relationships

 IS-A
 
In OO, the concept of IS-A is based on class inheritance or interface implementation. IS-A is a way of saying; "this thing is a type of that thing."
For example, a Lion is a type of Wild, so in OO terms we can say, "Lion IS-A Wild."  
You express the IS-A relationship in Java through the keywords extends
(for class inheritance) and implements (for interface implementation).

public class Wild{
// Wild Animal code goes here
}
public class Lion extends Wild {
// Important Lion-specific stuff goes here
// Don't forget Lion inherits accessible Wild members which
// can include both methods and variables.
}

HAS-A

HAS-A relationships are based on usage, rather than inheritance HAS-A is a way of saying; "this thing is a part of that thing."
For example, you can say the following, A Company HAS-A Department.
The code might look like this:

public class Company{
private Department department; // department is part of Company
}

No comments:

Post a Comment