java合成关系和聚合关系_Java中的聚合(HAS-A关系)

本文探讨了Java中的聚合(HAS-A关系),强调了聚合在代码重用方面的优势。通过Student和Address类的例子,展示了如何在Java中实现聚合。同时,文章还讨论了何时使用继承和聚合,并解释了两者的区别。聚合允许一个类包含另一个类的实例,而不需要从它继承。组合是一种更严格的聚合形式,其中包含的类为外部类提供了核心功能。
摘要由CSDN通过智能技术生成

java合成关系和聚合关系

Aggregation is a term which is used to refer one way relationship between two objects. For example, Student class can have reference of Address class but vice versa does not make sense.

聚合是一个术语,用于表示两个对象之间的单向关系 。 例如, 学生可以引用 地址类,反之亦然。

In Java, aggregation represents HAS-A relationship, which means when a class contains reference of another class known to have aggregation.

在Java中,聚合表示HAS-A关系 ,这意味着当一个类包含另一个已知具有聚合的类的引用时。

The HAS-A relationship is based on usage, rather than inheritance. In other words, class A has-a relationship with class B, if class A has a reference to an instance of class B.

HAS-A关系基于用法而不是继承。 换句话说,如果类A引用了类B的实例,则类A与类B具有关系。

Lets understand it by an example and consider two classes Student and Address. Each student has own address that makes has-a relationship but address has student not makes any sense. We can understand it more clearly using Java code.

让我们通过一个例子来理解它,并考虑两个类Student和Address。 每个学生都有自己的联系地址,但地址与学生无关。 使用Java代码,我们可以更清楚地了解它。

Class Address{
int street_no;
String city;
String state;
int pin;
Address(int street_no, String city, String state, int pin ){
this.street_no = street_no;
this.city = city;
this.state = state;
this.pin = pin;
}
}

class Student
{
  String name;
  Address ad;
}

Here in the above code, we can see Student class has-a relationship with Address class. We have draw an image too to demonstrate relation between these two classes..

在上面的代码中,我们可以看到Student类与Address类具有某种关系。 我们也绘制了一个图像来演示这两个类之间的关系。

Aggregation in Java
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值