logo

Java의 집계

클래스에 엔터티 참조가 있는 경우 이를 집계라고 합니다. 집계는 HAS-A 관계를 나타냅니다.

Java의 do 및 while 루프

상황을 생각해 보면 Employee 객체에는 id, name, emailId 등과 같은 많은 정보가 포함되어 있습니다. 여기에는 아래와 같이 도시, 주, 국가, 우편번호 등과 같은 자체 정보가 포함된 address라는 객체가 하나 더 포함되어 있습니다.

 class Employee{ int id; String name; Address address;//Address is a class ... } 

이러한 경우 Employee에는 엔터티 참조 주소가 있으므로 관계는 Employee HAS-A 주소입니다.

집계를 사용하는 이유는 무엇입니까?

  • 코드 재사용성을 위해.

집계의 간단한 예

이 예에서는 Circle 클래스에 Operation 클래스의 참조를 만들었습니다.

 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 

집계를 언제 사용합니까?

  • 코드 재사용은 is-a 관계가 없을 때 집계를 통해 가장 잘 달성됩니다.
  • 상속은 관련된 개체의 수명 동안 관계 is-a가 유지되는 경우에만 사용해야 합니다. 그렇지 않으면 집계가 최선의 선택입니다.

Aggregation의 의미 있는 예 이해

이 예에서 Employee에는 Address 개체가 있고 주소 개체에는 도시, 주, 국가 등과 같은 자체 정보가 포함되어 있습니다. 이러한 경우 관계는 Employee HAS-A 주소입니다.

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 
이 예제를 다운로드하세요