Frog is cry
getter_setter(day19) 본문
package day20.ex04_getter_setter;
public class Account {
private int balance;
public static final int MIMI_BAL = 0;
public static final int MAXI_BAL = 1000000;
public int getBalance() { // 게터 메소드를 이용해서 필드에 있는 값을 가져오는 역할을함
// 이 메소드를 호출하면 현재 balance필드에 저장된 값을 읽기참조할 수 있습니다.
return balance;
}
public void setBalance(int balance) { // 세터 메소드
// 이 메소드를 매개변수값과 함께 호출하면
// 매개변수의 값이 요구사항에 적합한 값인지 필터링(사전검사)하여
// 유효한 값인 경우에만 balance필드에 저장(쓰기참조)합니다.
if(MIMI_BAL < balance && MAXI_BAL > balance ) {
this.balance = balance;
}
}
}
package day20.ex04_getter_setter;
public class Account_Ex {
public static void main(String[] args) {
Account account = new Account();
account.setBalance(10000);
System.out.println("현재 잔고 : " + account.getBalance());
account.setBalance(-100);
System.out.println("현재 잔고 : " + account.getBalance());
account.setBalance(2000000);
System.out.println("현재 잔고 : " + account.getBalance());
account.setBalance(300000);
System.out.println("현재 잔고 : " + account.getBalance());
}
}
package day20.ex04_getter_setter;
//게터, 세터메소드 예제1
public class Car {
// 필드
private int speed;
private boolean stop;
// 생성자 없음
// 메소드
public int getSpeed() { // 현재 저장되어있는 speed(setter)를 가져옴
return speed;
}
public void setSpeed(int speed) { // setter : 외부에서 전달된 값을 유효성을 검사할때 사용함
// 다른필드에 저장되어있는 값을 세팅하는것
if(speed < 0) {
this.speed = 0; // 매개변수로 넘어온 값이 무효하므로 0으로 세팅함
return;
}else {
this.speed = speed; // 매개변수로 넘어온 값이 무효하므로 0으로 세팅함
}
}
public boolean isStop() {
return stop;
}
public void setStop(boolean stop) {
this.stop = stop;
System.out.println("setStop 현재속도 B : " + this.speed);
this.speed = 0;
}
}
package day20.ex04_getter_setter;
public class Car_Ex {
public static void main(String[] args) {
Car myCar = new Car();
// 잘못된 속도변경
myCar.setSpeed(-50);
System.out.println("현재속도A : " + myCar.getSpeed());
//
// 올바른 속도변경
myCar.setSpeed(160); // setSpeed라는 메소드를 이용하기위해선 (160)의 형식처럼 값을 넣어줘야함
//
//멈춤
if(!myCar.isStop()) {
myCar.setStop(true);
}
System.out.println("현재속도C : " + myCar.getSpeed());
}
}
'JAVA > 국비수업' 카테고리의 다른 글
상속(day20) (0) | 2020.07.27 |
---|---|
이전복습 (day19) (0) | 2020.07.24 |
패키지-import(Day19) (0) | 2020.07.24 |
파이널(day18) (0) | 2020.07.23 |
싱글톤(day18) (0) | 2020.07.23 |
Comments