- 캡슐화
: 한 개체를 다른 개체로부터 보호하는 것. 특정 클래스의 데이터에 접근하려면 해당 클래스의 메서드를 통해서 접근해야 한다.
- 예제: 캡슐화 적용 X
객체이름.멤버변수이름 = value;
위 형태와 같이 코드를 작성하면 직접적으로 MotorBike의 인스턴스 변수에 접근 가능하다.
그러나 MotorBikeRunner과 별개의 클래스이기 떄문에 좋지 않다.
-> 캡슐화 파괴!!
- MotorBikeRunner.java
public class MotorBikeRunner {
public static void main(String[] args) {
MotorBike ducati = new MotorBike();
MotorBike honda = new MotorBike();
ducati.start();
honda.start();
//직접적으로 MotorBike의 인스턴스 변수에 접근 가능
ducati.speed = 100;
honda.speed = 80;
}
}
- MotorBike.java
public class MotorBike {
//멤버 변수
int speed;
//메서드
void start() {
System.out.println("Bike Started");
}
}
- 예제: 캡슐화 적용
- MotorBikeRunner.java
public class MotorBikeRunner {
public static void main(String[] args) {
MotorBike ducati = new MotorBike();
MotorBike honda = new MotorBike();
ducati.start();
honda.start();
ducati.setSpeed(100);
//System.out.println(ducati.getSpeed());
//honda.setSpeed(80);
System.out.println(honda.getSpeed()); //0 출력 (default 값)
}
}
- MotorBike.java
public class MotorBike {
//클래스 외부에서 접근 불가
private int speed; //멤버 변수
public void setSpeed(int speed) { //지역 변수
System.out.println(speed); //100 출력
System.out.println(this.speed); //0 출력 (speed 멤버 변수의 default 값. 설정x -> 0)
this.speed = speed;
System.out.println(this.speed); //100 출력
}
public int getSpeed() {
return this.speed;
}
//메서드
void start() {
System.out.println("Bike Started");
}
}
* 이클립스에서 getter, setter 자동 생성하는 방법
: 마우스 우클릭 > source > Generate Getters and Setters
* getter와 setter 뿐만 아니라 객체 내 로직을 캡슐화하여 외부 코드를 많이 수정하지 않고 쉽게 로직을 바꿀 수 있다.
'Java' 카테고리의 다른 글
| 캡슐화, 추상화 개념 및 차이 (0) | 2023.05.31 |
|---|---|
| [java] eclipse에서 디버깅하는 방법 (0) | 2023.05.31 |
| 메서드 오버로딩 / 오버라이딩 / Refactoring (0) | 2023.05.30 |
| [java] eclipse 단축키 모음 (0) | 2023.05.30 |
| jshell 사용법 (0) | 2023.05.24 |