java为什么要使用聚合,Java使用聚合

如果一个类有一个实体引用,它被称为聚合。聚合代表有关系。

考虑情况,Employee对象包含许多信息,如id、名称、emailId等等。它包含一个对象叫地址,其中包含它自己的信息,如城市,国家,国家,zipcode等如下考虑。

class Employee{

int id;

String name;

Address address;//Address is a class

...

}

在这种情况下,员工有一个实体引用地址,所以关系是员工有一个地址。

为什么使用聚合?

代码可重用性。

聚合的简单示例

在这个例子中,我们创建了圆类中引用的操作类。

class Operation{

int square(int n){

return n*n;

}

}

class Circle{

Operation op;//aggregation

double pi=3.14;

double area(int radius){

op=new Operation();

int rsquare=op.square(radius);//code reusability (i.e. delegates the method call).

return pi*rsquare;

}

public static void main(String args[]){

Circle c=new Circle();

double result=c.area(5);

System.out.println(result);

}

}

Output:78.5

当使用聚合吗?

代码重用也最好通过聚合当没有是一个关系。

继承应该只有在使用的关系是维持在对象的生命周期;否则,聚合是最好的选择。

了解聚合的有意义的例子

在这个例子中,员工有一个对象的地址,地址对象包含它自己的信息,如城市、州、国家等。在这种情况下员工关系有一个地址。

Address.java

public class Address {

String city,state,country;

public Address(String city,String state,String country) {

this.city = city;

this.state = state;

this.country = country;

}

}

Emp.java

public class Emp {

int id;

String name;

Address address;

public Emp(int id,String name,Address address) {

this.id = id;

this.name = name;

this.address=address;

}

void display(){

System.out.println(id+" "+name);

System.out.println(address.city+" "+address.state+" "+address.country);

}

public static void main(String[] args) {

Address address1=new Address("gzb","UP","india");

Address address2=new Address("gno","UP","india");

Emp e=new Emp(111,"varun",address1);

Emp e2=new Emp(112,"arun",address2);

e.display();

e2.display();

}

}

Output:111 varun

gzb UP india

112 arun

gno UP india

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值