Java中的IS-A关系和HAS-A关系有什么区别?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36162714/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the difference between IS -A relationship and HAS-A relationship in Java?
提问by Milan
I am new to JAVA and just started learning IS-A and HAS-A relation but couldn't get much .I want to visualize how these two are different and when we should be using IS-A and HAS-A ?
我是 JAVA 新手,刚开始学习 IS-A 和 HAS-A 关系,但学得不多。我想想象一下这两者有何不同以及我们何时应该使用 IS-A 和 HAS-A?
采纳答案by Neha Dadhich
An IS-A relationship is inheritances. The classes which inherit are known as sub classes or child classes. On the other hand, HAS - A relationship is composition
IS-A 关系是继承。继承的类称为子类或子类。另一方面,HAS - A 关系是组合
In OOP, IS - A relationship is completely inheritance. This means, that the child class is a type of parent class. For example, an apple is a fruit. So you will extend fruit to get apple.
在 OOP 中,IS - 关系是完全继承的。这意味着,子类是父类的一种。例如,苹果是一种水果。所以你会延长水果来得到苹果。
class Apple extends Fruit{
.
.
}
On the other hand, composition means creating instances which have references to other objects. For example, a room has a table. So you will create a class room and then in that class create an instance of type table.
另一方面,组合意味着创建引用其他对象的实例。例如,一个房间有一张桌子。因此,您将创建一个教室,然后在该类中创建一个 table 类型的实例。
class Room{
:
Table table = new Table ();
:
:
}
A HAS-A relationship is dynamic (run time ) binding while inheritance is a static (compile time ) binding. If you just want to reuse the code and you know that the two are not of same kind use composition. For example, you cannot inherit an oven from a kitchen. A kitchen HAS-A oven. When you feel there is a natural relationship like Apple is a Fruit use inheritance.
HAS-A 关系是动态(运行时)绑定,而继承是静态(编译时)绑定。如果您只想重用代码并且您知道两者不是同一种,请使用组合。例如,您不能从厨房继承烤箱。厨房有烤箱。当你觉得有像 Apple 是 Fruit 一样的自然关系时,请使用继承。
回答by John
Foo is-a Bar:
Foo is-a 酒吧:
public class Foo extends Bar{}
Foo has-a Bar
Foo has-a Bar
public class Foo {
private Bar bar;
}