>  기사  >  Java  >  자바 협회

자바 협회

WBOY
WBOY원래의
2024-08-30 16:03:31768검색

Java의 연관은 객체를 통해 설정된 두 클래스 간의 관계 또는 연결입니다. 연관은 클래스가 다른 클래스에 대해 알고 있으며 다른 클래스에 대한 참조를 보유함을 나타냅니다. 이는 인스턴스 필드를 사용하여 Java로 구현되므로 "has-a" 관계로 설명할 수 있습니다. 각 클래스가 다른 클래스에 대한 참조를 가지므로 연관 관계는 양방향일 수 있습니다. 연관 관계는 객체가 서로 연결되는 방식을 나타냅니까? 그들은 어떻게 서로 소통합니까? 그리고 그들은 서로의 기능을 어떻게 사용합니까? 연관 관계는 일대일, 다대일, 일대다, 다대다의 네 가지 유형이 있습니다.

자바의 협회 형태

결합의 두 가지 형태는 집합(Aggregation)과 합성(Composition)입니다.

무료 소프트웨어 개발 과정 시작

웹 개발, 프로그래밍 언어, 소프트웨어 테스팅 등

1. 집계

집계는 엔터티 참조를 통해 설정된 두 클래스 간의 관계입니다. 이는 has-a 및 부분 또는 전체 관계로 설명될 수 있습니다. 집계는 단방향 또는 단방향 연결인 연결 형식입니다. 예를 들어 고객이 주문을 받을 수 있지만 그 반대는 불가능하므로 단방향입니다.

class Customer{
int cid;
String cname;
Order ordering;
}

2. 구성

구성 관계는 두 클래스(또는 엔터티)가 서로 크게 의존하는 제한된 형태의 집계입니다. 구성된 객체는 다른 엔터티 없이는 존재할 수 없습니다. 구성은 관계의 일부로 설명할 수 있습니다.

Java의 연관 예시

다음은 Java에서 연관의 다양한 예입니다.

예 #1 – 협회 관계

여기서 Association 관계를 좀 더 명확하게 이해하기 위해 다음 예시를 통해 Java 코드를 작성해보겠습니다.

코드:

package demo;
import java.io.*;
class Department
{
private String dname;
public void setDepartmentName(String cname)
{
this.dname = cname;
}
public String getDepartmentName()
{
return this.dname;
}
}
class Emp
{
public String ename;
public void setEmployeeName(String ename)
{
this.ename = ename;
}
public String getEmployeeName()
{
return this.ename;
}
}
class demo
{
public static void main (String[] args)
{
Department d = new Department();
Department d1 = new Department();
Emp e = new Emp();
Emp e1 = new Emp();
d.setDepartmentName("Sales");
d1.setDepartmentName("Accounting");
e.setEmployeeName("John");
e1.setEmployeeName("Joseph");
System.out.println(e.getEmployeeName() + " is working in " + d.getDepartmentName() + ".");
System.out.println(e1.getEmployeeName() + " is working in " + d1.getDepartmentName() + ".");
}
}

출력:

자바 협회

위 코드에서 Company와 Employee라는 두 클래스는 개체를 통해 일대다 관계를 나타냅니다. Company 클래스에는 많은 직원이 있을 수 있기 때문입니다.

예시 #2 – 집계 관계

다음으로, 다음 예시를 통해 집계 관계를 더욱 명확하게 이해하기 위해 Javacode를 작성해보겠습니다.

코드:

import java.io.*;
import java.util.*;
class Customer
{
String cname;
int cid ;
String type;
public static int cpp=0,ccod=0;
Customer(String cname, int cid, String type)
{
this.cname = cname;
this.cid = cid;
this.type = type;
if(type=="prepaid")
cpp++;
else
ccod++;
}
}
class Order
{
String type;
//list of customer Objects associated with customer class as with its Object(s). */
private List<Customer> customers;
public void setCustomers(String type, List<Customer> customers)
{
this.type = type;
this.customers = customers;
}
public List<Customer> getCustomers()
{
return customers;
}
}
class OnlineStore
{
// list of order Objects which associated with order as with its objects.
private List<Order> orders;
public void setnoCustomer( List<Order> orders)
{
this.orders = orders;
}
// count total customers of all orders in a given purchases
public int getnoCustomer()
{
int noOfOrders = 0;
List<Customer> customers;
for(Order dept : orders)
{
customers = dept.getCustomers();
for(Customer s : customers)
{
noOfOrders++;
}
}
return noOfOrders;
}
}
class demo
{
public static void main (String[] args)
{
Customer c1 = new Customer("Mia", 1, "prepaid");
Customer c2 = new Customer("Priya", 2, "prepaid");
Customer c3 = new Customer("John", 1, "COD");
Customer c4 = new Customer("Rahul", 2, "COD");
List <Customer> cu1 = new ArrayList<Customer>();
cu1.add(c1);
cu1.add(c2);
// making a List of COD Customers
List <Customer> cu2 = new ArrayList<Customer>();
cu2.add(c3);
cu2.add(c4);
Order pp = new Order();
pp.setCustomers("prepaid", cu1);
Order cod = new Order();
cod.setCustomers("COD", cu2);
List <Order> orders = new ArrayList<Order>();
orders.add(pp);
orders.add(cod);
// creating an OnlineStore instance.
OnlineStore purchase = new OnlineStore();
purchase.setnoCustomer(orders);
System.out.print("Number of Customers placed order are : ");
System.out.println(purchase.getnoCustomer());
System.out.print("Number of Customers placed prepaid order are : ");
System.out.println(Customer.cpp);
System.out.print("Number of Customers placed cod order are : ");
System.out.println(Customer.cpp);
}
}

출력:

자바 협회

위 코드와 같이 온라인 상점에는 no. 선불 및 COD와 같은 주문. 모든 유형의 주문에는 번호가 없습니다. 고객, 객체와 관련된 OnlineStore 클래스 또는 아니오. Order 클래스의 개체 중 하나입니다. onlineStore 클래스는 Objects 및 Order 클래스를 통해 Order 클래스와 연결됩니다. 또한 Customer 클래스의 개체를 참조합니다. 즉, Has-A 관계를 나타내는 개체를 통해 Customer 클래스와 관련되어 있음을 의미합니다.

예 #3 – 구성 관계

다음으로 다음 예시를 통해 Composition 관계를 좀 더 명확하게 이해할 수 있도록 Java 코드를 작성해보겠습니다.

코드:

class Car
{
private String color;
private int wheels;
public void carFeatures()
{
System.out.println("The color of the car is "+color + " and number of wheels are " + wheels);
}
public void setColor(String color)
{
this.color = color;
}
public void setwheels(int wheels)
{
this.wheels = wheels;
}
}
class Maruti extends Car
{
public void setStart()
{
MarutiEngine e = new MarutiEngine();
e.run();
}
}
class MarutiEngine extends Maruti
{
public void run()
{
System.out.println("Engine is running...");
}
public void stop()
{
System.out.println("Engine is not running... ");
}
}
public class demo
{
public static void main(String[] args)
{
Maruti m1 = new Maruti();
m1.setwheels(4);
m1.setColor("White");
m1.carFeatures();
m1.setStart();
}
}

출력:

자바 협회

위 코드에서와 같이 Car는 Maruti 클래스의 슈퍼클래스입니다. 즉, Car는 no를 가질 수 있습니다. Maruti 자동차의 경우 Maruti는 MarutiEngine을 그 일부로 사용합니다. Maruti가 존재하지 않으면 MarutiEngine도 종료되지 않습니다. 따라서 Maruti와 MarutiEngine 클래스는 구성 관계를 설명합니다.

Java에서 연관 사용:

위에서 본 것처럼 코드 재사용을 위해 연결이 필요합니다. 예를 들어 위의 두 클래스인 Customer 클래스, Order 클래스, OnlineStore 클래스를 사용하여 고객 정보를 관리하므로 프로그래머는 동일한 코드를 반복해서 사용할 필요가 없습니다.

결론

Java에서는 객체를 설정하여 두 클래스 간의 관계인 연관을 설정합니다. Association의 형태에는 Aggregation과 Composition이 있습니다. Java에서 연결의 주요 목적은 코드 재사용을 위한 것입니다.

위 내용은 자바 협회의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
이전 기사:자바 스레드로컬다음 기사:자바 스레드로컬