Java中的IS-A关系和HAS-A关系有什么区别? [英] What is the difference between IS -A relationship and HAS-A relationship in Java?

查看:263
本文介绍了Java中的IS-A关系和HAS-A关系有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是JAVA的新手,刚刚开始学习IS-A和HAS-A关系,但却无法获得太多。我想想象一下这两者是如何不同的以及我们何时应该使用IS-A和HAS-A?

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 ?

推荐答案

IS-A关系是遗产。继承的类称为子类或子类。另一方面,HAS - A关系是组合

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

在OOP中,IS - 关系是完全继承的。这意味着,子类是一种父类。例如,苹果是一种水果。所以你会扩展水果以获得苹果。

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.

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.

class Room{

:
Table table = new Table ();
:
:
}

HAS-A关系是动态(运行时)绑定,而继承是静态(编译时)绑定。
如果您只是想重用代码,并且您知道两者不是同一类,请使用组合。例如,你不能从厨房烤箱。厨房有一个烤箱。
当你觉得像Apple这样的自然关系是Fruit使用继承。

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 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.

这篇关于Java中的IS-A关系和HAS-A关系有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆