예제 코드 분석
s0501~s0504구조 파악
s0501: 정적 속성과 정적 메서드를 가진Calculator클래스를, 인스턴스 속성과 인스턴스 메서드를 가진Calculator3클래스로 변화시킨다.s0502: 인스턴스의 속성을 변경할 때, 속성에 직접 접근해 할당(cat.name = "body")하지 않고 메서드 호출(cat.setName("body"))을 통해 인스턴스의 속성을 변경한다.s0503: 메서드의 매개 변수 유무, 반환값 유무, 변수의 유효 범위에 대한 예시다. 매개 변수는 매개 변수가 속한 메서드 내에서 유효함을 알 수 있다.s0504: 매개 변수 자료형 종류에 따른 동작의 차이를 나타낸다. 메서드의 매개 변수에 참조형 값을 전달할 경우, 메서드에서 객체 변수의 값을 변경할 수 있음에 유의한다.
간단 클래스 작성
Calculator등 유틸 클래스 구현
다음 예제의 Calculator 클래스는 정적 메서드 add와 인스턴스 메서드 add를 포함한다. 정적 메서드 add는 도트 연산자(.) 없이 메서드 이름만으로 메서드를 호출하고, 인스턴스 메서드 add는 인스턴스를 생성한 뒤 <인스턴스 이름>.<메서드 이름>으로 메서드를 호출한다.
public class Calculator {
long operandOne;
long operandTwo;
static long add(long a, long b) {
return a + b;
}
long add() {
return this.operandOne + this.operandTwo;
}
public static void main(String[] args) {
// 정적 메서드 사용
long operandOne = 21;
long operandTwo = 84;
System.out.printf("%d + %d = %d\n", operandOne, operandTwo, add(operandOne, operandTwo));
// 인스턴스 메서드 사용
Calculator calculator = new Calculator();
calculator.operandOne = 21;
calculator.operandTwo = 84;
System.out.printf("%d + %d = %d\n", calculator.operandOne, calculator.operandTwo, calculator.add());
}
}생성자 오버로딩 연습
여러 생성자를 가진 클래스 구현
다음 Book 클래스는 세 가지 생성자를 포함하며, 생성자마다 매개 변수 개수에 차이가 있어 메서드 오버로딩이 발생한다.
public class Book {
String title = "무제";
String author = "무명";
Book() {}
Book(String title) {
this.title = title;
}
Book(String title, String author) {
this.title = title;
this.author = author;
}
public static void main(String[] args) {
Book bookOne = new Book();
Book bookTwo = new Book("오디세이아");
Book bookThree = new Book("1984", "조지 오웰");
System.out.printf("제목: %s, 작가: %s\n", bookOne.title, bookOne.author);
System.out.printf("제목: %s, 작가: %s\n", bookTwo.title, bookTwo.author);
System.out.printf("제목: %s, 작가: %s\n", bookThree.title, bookThree.author);
}
}도메인 요구사항 정리, 도메인 클래스 구현, 캡슐화 적용
설명
- 계좌/학생 등 도메인 선택 및 정리
- 설계한 클래스 구현 및 테스트
- 필드 은닉, 메서드로 제어
다음 Account 클래스는 예금주, 계좌번호, 잔액 속성을 지니며 입금 및 송금 기능이 있다.
package mission05;
import java.util.HashMap;
public class Account {
static HashMap<String, Account> registry = new HashMap<>();
private String accountHolder; // 예금주
private String accountNo; // 계좌번호
private long balance = 0L; // 잔액
Account(String accountHolder, String accountNo) {
this.accountHolder = accountHolder;
this.accountNo = accountNo;
}
static void register(Account account) {
registry.put(account.accountNo, account);
}
// 계좌에 돈을 입금한다.
void deposit(long won) {
this.balance += won;
}
// 타 계좌로 돈을 송금한다.
void remit(long won, String accountNo) {
if (this.balance < won) {
System.out.println("잔액이 부족합니다.");
return;
}
if (!registry.containsKey(accountNo)) {
System.out.println("상대 계좌가 존재하지 않습니다.");
}
Account targetAccount = registry.get(accountNo);
this.balance -= won;
targetAccount.balance += won;
System.out.printf("%s 계좌로 %d원을 송금했습니다.\n", accountNo, won);
System.out.printf("%s 계좌의 잔액은 %d원입니다.\n", this.accountHolder, this.balance);
System.out.printf("%s 계좌의 잔액은 %d원입니다.\n", targetAccount.accountHolder, targetAccount.balance);
}
public static void main(String[] args) {
// 두 개의 Account 인스턴스를 생성한다.
Account gildongAccount = new Account("홍길동", "73821722839462");
Account chulsuAccount = new Account("이철수", "63551622738491");
// 생성한 Account 계좌를 HashMap에 삽입한다.
Account.register(gildongAccount);
Account.register(chulsuAccount);
// 두 계좌에 각각 1백만 원을 입금한다.
gildongAccount.deposit(1_000_000);
chulsuAccount.deposit(1_000_000);
// 홍길동의 계좌로부터 이철수의 계좌로 30만 원을 송금한다.
gildongAccount.remit(300_000, "63551622738491");
// 출력:
// 63551622738491 계좌로 300000원을 송금했습니다.
// 홍길동 계좌의 잔액은 700000원입니다.
// 이철수 계좌의 잔액은 1300000원입니다.
}
}