>  기사  >  Java  >  Java의 캡슐화

Java의 캡슐화

王林
王林원래의
2024-08-30 15:59:54912검색

캡슐화는 Java의 네 가지 기본 객체 지향 프로그래밍 개념 중 하나입니다. 이것의 주요 아이디어는 사용자에게 구현 세부 사항을 숨기는 것입니다. 즉, 캡슐화는 데이터를 단일 단위로 묶어서 외부 세계에서 해당 데이터에 접근하는 것을 방지하는 것입니다. 데이터가 다른 클래스로부터 숨겨지기 때문에 이 프로세스를 데이터 숨기기라고 합니다. 전구의 작동을 예로 들어 생각해 보겠습니다. 사용해도 전구 뒤에서 작동하는지 알 수 없습니다.  하지만 Java Encapsulation의 경우 수정자를 사용하여 데이터에 접근하는 것이 가능합니다. 다음 섹션에서 이에 대해 살펴보겠습니다.

Java에서 캡슐화는 어떻게 작동하나요?

Java에서 캡슐화 작업:

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

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

  • 클래스의 속성이나 변수를 비공개로 선언

예를 들어 Employee 클래스를 생성합니다. 아래와 같이 변수를 비공개로 설정해야 합니다.

private String EmpName;
private int EmpID;
private int EmpSal;
  • 클래스에 공용 메소드를 생성하여 속성이나 변수를 가져오고 설정합니다.

다음은 Employee 클래스의 다양한 개인 변수에 대한 get 메서드와 set 메서드입니다.

코드:

public int getEmpSal()
{
return EmpSal;
}public String getEmpName()
{
return EmpName;
}
public int getEmpID()
{
return EmpID;
}
public void setEmpSal( int EmpSal)
{
this.EmpSal = EmpSal;
}
public void setEmpName(String EmpName)
{
this.EmpName = EmpName;
}
public void setEmpID( int EmpID)
{
this.EmpID = EmpID;
}

이러한 메소드를 사용하면 클래스를 쓰기 전용 또는 읽기 전용으로 설정할 수 있습니다. 즉, 필요한 경우 이러한 메소드를 건너뛸 수 있습니다.

Java 캡슐화의 장점

Encapsulation의 장점은 다음과 같습니다.

  • 신청의 단순성
  • 요구사항에 따라 코드를 재사용하거나 수정하는 기능
  • 데이터 접근성 제한
  • 코드가 캡슐화되어 있어 단위 테스트가 용이함

Java Bean 클래스는 클래스의 모든 데이터 멤버가 비공개이므로 완전히 캡슐화된 클래스의 한 예입니다.

Java 캡슐화의 예

getter 및 setter 메서드를 모두 사용한 캡슐화의 예를 살펴보겠습니다. 이를 위해 기본 메서드를 사용하는 클래스와 가져오기 및 설정 메서드를 사용하는 클래스 등 2개의 클래스를 만듭니다.

예시 #1

Employee.java

코드:

//Java program for Encapsulation with both read and write
public class Employee {
//private variables which can be accessed by public methods of the class
private String EmpName;
private int EmpID;
private int EmpSal;
// get method to access the private integer variable EmpSal
public int getEmpSal()
{
return EmpSal;
}
// get method to access the private string variable EmpName
public String getEmpName()
{
return EmpName;
}
// get method to access the private integer variable EmpID
public int getEmpID()
{
return EmpID;
}
// set method to access the private integer variable EmpSal
public void setEmpSal( int EmpSal)
{
this.EmpSal = EmpSal;
}
// set method to access the private string variable EmpName
public void setEmpName(String EmpName)
{
this.EmpName = EmpName;
}
// set method to access the private integer variable EmpID
public void setEmpID( int EmpID)
{
this.EmpID = EmpID;
}
}
  • EmployeeEncaps.java

코드:

public class EmployeeEncaps {
public static void main(String[] args) {
Employee EmpObj= new Employee(); //object of the class Employee
//passing the values to the methods using object
EmpObj.setEmpName("Anna");
EmpObj.setEmpSal(30000);
EmpObj.setEmpID(670311);
// Printing values of the variables
System.out.println("Employee's Name: " + EmpObj.getEmpName());
System.out.println("Employee's ID: " + EmpObj.getEmpID());
System.out.println("Employee's Salary: " + EmpObj.getEmpSal());
}
}

출력:

Java의 캡슐화

Employee 클래스는 변수가 비공개이므로 위 프로그램에서 캡슐화됩니다. 메소드를 가져오고 설정하므로 구현을 읽고 쓸 수 있습니다. EmpName, EmpSal, EmpID와 같은 전용 변수는 이러한 메서드를 사용하여 액세스하고 개체를 사용하여 메서드를 호출하면 표시됩니다.

이제 읽기 전용 클래스에서 캡슐화가 어떻게 작동하는지 살펴보겠습니다.

예시 #2

  • Employee.java

코드:

//Java program for Encapsulation with read permission
public class Employee {
//private variables which can be accessed by public methods of the class
private String EmpName = "Adam";
private int EmpID = 670388;
private int EmpSal = 35000;
// get method to access the private integer variable EmpSal
public int getEmpSal()
{return EmpSal;
}// get method to access the private string variable EmpName
public String getEmpName()
{
return EmpName;
}
// get method to access the private integer variable EmpID
public int getEmpID()
{
return EmpID;
}
}
  • EmployeeEncaps.java

코드:

public class EmployeeEncaps {
public static void main(String[] args) {
Employee EmpObj= new Employee(); //object of the class Employee
// Printing values of the variables
System.out.println("Employee's Name: " + EmpObj.getEmpName());
System.out.println("Employee's ID: " + EmpObj.getEmpID());
System.out.println("Employee's Salary: " + EmpObj.getEmpSal());
}
}

출력:

Java의 캡슐화

첫 번째 예와 마찬가지로 개인 변수도 사용하고 있습니다. 차이점은 클래스의 개인 변수에 대한 값을 설정하기 위해 set 메소드를 사용하지 않는다는 것입니다. 대신 변수에 값을 직접 할당합니다.

이제 쓰기 전용 클래스로 넘어갈 수 있습니다.

예시 #3

  • Employee.java

코드:

//Java program for Encapsulation with write permission
public class Employee {
//private variables which can be accessed by public methods of the class
private String EmpName;
private int EmpID;
private int EmpSal;
// set method to access the private integer variable EmpSal
public void setEmpSal( int EmpSal)
{
this.EmpSal = EmpSal;
//for sample output
System.out.println("Employee's Salary: " + EmpSal);
}
// set method to access the private string variable EmpName
public void setEmpName(String EmpName)
{
this.EmpName = EmpName;
//for sample output
System.out.println("Employee's Name: " + EmpName);
}// set method to access the private integer variable EmpID
public void setEmpID( int EmpID)
{
this.EmpID = EmpID;
//for sample output
System.out.println("Employee's ID: " + EmpID);
}
}
  • EmployeeEncaps.java

코드:

public class EmployeeEncaps {
public static void main(String[] args) {
Employee EmpObj= new Employee(); //object of the class Employee
//passing the values to the methods using object
EmpObj.setEmpName("Iza");
EmpObj.setEmpID(670472);
EmpObj.setEmpSal(48000);
}
}

출력:

Java의 캡슐화

위 예에서는 쓰기 전용 클래스를 달성하기 위해 get 메소드를 사용하지 않습니다. 즉, 여기서 변수를 변경하거나 검색할 수 없습니다. 값을 가져오는 것이 불가능하므로 샘플 출력을 위해 set 메소드 내부에서 print 를 사용합니다.

결론

캡슐화는 모든 구현 세부 사항을 숨기고 데이터를 래핑하는 OOP 개념입니다. 이는 개인 변수 및 변수에 액세스하기 위한 가져오기 및 설정과 같은 메소드를 사용하여 달성할 수 있습니다. 캡슐화의 주요 장점은 유연성, 데이터 은닉, 테스트 용이성, 재사용성입니다.

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

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