Created
January 19, 2014 03:25
-
-
Save rajeevprasanna/8500118 to your computer and use it in GitHub Desktop.
Has-A relationship example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package inheritanceIsaAndHasA.hasA; | |
public class Animal { | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package inheritanceIsaAndHasA.hasA; | |
public class Halter { | |
public void tie(LeadRope aRope) { | |
// Do the actual tie work here | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package inheritanceIsaAndHasA.hasA; | |
public class LeadRope { | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment