Skip to content

Instantly share code, notes, and snippets.

@rajeevprasanna
Created January 19, 2014 03:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rajeevprasanna/8500118 to your computer and use it in GitHub Desktop.
Save rajeevprasanna/8500118 to your computer and use it in GitHub Desktop.
Has-A relationship example
package inheritanceIsaAndHasA.hasA;
public class Animal {
}
package inheritanceIsaAndHasA.hasA;
public class Halter {
public void tie(LeadRope aRope) {
// Do the actual tie work here
}
}
package inheritanceIsaAndHasA.hasA;
public class Horse extends Animal {
// Horse class has an instance variable of type Halter, so you can say that
// "Horse HAS-A Halter."
private Halter myHalter = new Halter();
// HAS-A relationships allow you to design classes that follow good OO
// practices by not having monolithic classes that do a gazillion different
// things. Classes (and their resulting objects) should be specialists.
// "specialized classes can actually help reduce bugs." The more specialized
// the class, the more likely it is that you can reuse the class in other
// applications. If you put all the Halter-related code directly into the
// Horse class, you'll end up duplicating code in the Cow class,
// UnpaidIntern class, and any other class that might need Halter behavior.
// By keeping the Halter code in a separate, specialized Halter class, you
// have the chance to reuse the Halter class in multiple applications
public void tie(LeadRope rope) {
myHalter.tie(rope); // Delegate tie behavior to the
// Halter object
}
}
package inheritanceIsaAndHasA.hasA;
public class LeadRope {
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment