One of the advantages of an Object-Oriented programming language is code reuse. There are two ways we can do code reuse either by the vimplementation of inheritance (IS-A relationship), or object composition (HAS-A relationship). Although the compiler and Java virtual machine (JVM) will do a lot of work for you when you use inheritance, you can also get at the functionality of inheritance when you use composition.
IS-A Relationship:
In object-oriented programming, the concept of IS-A is a totally based on Inheritance, which can be of two types Class Inheritance or Interface Inheritance. It is just like saying "A is a B type of thing". For example, Apple is a Fruit, Car is a Vehicle etc. Inheritance is uni-directional. For example, House is a Building. But Building is not a House.
It is a key point to note that you can easily identify the IS-A relationship. Wherever you see an extends keyword or implements keyword in a class declaration, then this class is said to have IS-A relationship.
HAS-A Relationship:
Composition(HAS-A) simply mean the use of instance variables that are references to other objects. For example Maruti has Engine, or House has Bathroom.
Let’s understand these concepts with an example of Car class.
http://www.w3resource.com/java-tutorial/inheritance-composition-relationship.php
本文探讨了面向对象编程中的两大核心概念:继承(IS-A)与组合(HAS-A)。通过实例说明了如何利用这两种关系实现代码复用,特别强调了它们之间的区别及其应用场景。
811

被折叠的 条评论
为什么被折叠?



