Chapter 06 클래스
객체는 필드와 메서드로 이루어져있으며 객체 간의 관계는 집합 관계와 사용 관계 및 상속 관계가 있다.
객체 지향 프로그래밍의 대표적인 세 가지 특징으로는 캡슐화와 상속 및 다형성이 있다.
객체 생성을 위한 일종의 설계도이며 클래스를 인스턴스화 하여 객체를 생성한다.
public class Car {
String model = "제네시스"; // 고유 데이터
int speed = 300; // 상태 데이터
boolean start = true; // 상태 데이터
Tire tire = new Tire(); // 부품 데이터
}
매개변수의 타입 또는 개수 또는 순서 중 한 개라도 다르게 선언해야한다.
매개변수의 개수와 상관없이 매개값을 전달할 수 있다.
int sum(int ... values) { }
int result1 = sum(1, 2, 3);
int result2 = sum(1, 2, 3, 4, 5);
정적 필드와 정적 메서드로 구성된다. 정적 메서드와 정적 블록에서는 인스턴스 멤버와 this 를 사용할 수 없다. 인스턴스 멤버는 객체를 생성해야만 접근할 수 있기 때문이다.
public class Test {
int iv; // 인스턴스 변수
static int cv; // 클래스 변수
public void sum(int num1, int num2) { // 매개변수
int lv; // 지역 변수
}
}
static final double PI = 3.14159;
은행 잔고 관리 예제 문제를 풀어보았다.
먼저 문제를 풀어보고 모범 답안을 확인하면서 다시 풀어보았다.
입력받은 값으로 객체를 생성하고 findAccount 메서드로 객체 배열에서 찾으려는 객체 주소를 반환하는 흐름이 중요한 것 같다.
public class UpgradeBankApplication {
private static Account[] accountArray = new Account[100];
private static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
boolean run = true;
while(run) {
System.out.println("----------------------------------------------");
System.out.println("1.계좌생성 | 2.계좌목록 | 3.예금 | 4.출금 | 5.종료");
System.out.println("----------------------------------------------");
System.out.print("선택> ");
int selectNo = Integer.parseInt(scanner.nextLine());
if (selectNo == 1) {
createAccount();
} else if (selectNo == 2) {
accountList();
} else if (selectNo == 3) {
deposit();
} else if (selectNo == 4) {
withdraw();
} else if (selectNo == 5) {
run = false;
}
}
System.out.println("프로그램 종료");
}
// 계좌 생성
private static void createAccount() {
System.out.println("------------------");
System.out.println("계좌생성");
System.out.println("------------------");
System.out.print("계좌번호: ");
String ano = scanner.nextLine();
System.out.print("계좌주: ");
String owner = scanner.nextLine();
System.out.print("초기입금액: ");
int balance = Integer.parseInt(scanner.nextLine());
Account newAccount = new Account(ano, owner, balance);
for(int i=0; i<accountArray.length; i++) {
if (accountArray[i] == null) {
accountArray[i] = newAccount;
System.out.println("결과: 계좌가 생성되었습니다.");
break;
}
}
}
// 계좌 목록
private static void accountList() {
System.out.println("------------------");
System.out.println("계좌목록");
System.out.println("------------------");
for (Account a : accountArray) {
if (a != null) {
System.out.print(a.getAccountNum());
System.out.print(" ");
System.out.print(a.getName());
System.out.print(" ");
System.out.println(a.getBalance());
}
}
}
// 예금
private static void deposit() {
System.out.println("------------------");
System.out.println("예금");
System.out.println("------------------");
System.out.print("계좌번호: ");
String ano = scanner.nextLine();
System.out.print("예금액: ");
int money = Integer.parseInt(scanner.nextLine());
Account account = findAccount(ano);
if(account == null) {
System.out.println("일치하는 계좌가 존재하지 않습니다.");
return;
}
account.setBalance(account.getBalance() + money);
System.out.println("결과: 예금이 성공되었습니다.");
}
// 출금
private static void withdraw() {
System.out.println("------------------");
System.out.println("출금");
System.out.println("------------------");
System.out.print("계좌번호: ");
String ano = scanner.nextLine();
System.out.print("출금액: ");
int money = Integer.parseInt(scanner.nextLine());
Account account = findAccount(ano);
if(account == null) {
System.out.println("일치하는 계좌가 존재하지 않습니다.");
return;
}
account.setBalance(account.getBalance() - money);
System.out.println("결과: 출금이 성공되었습니다.");
}
// 계좌 찾기
private static Account findAccount(String ano) {
Account account = null;
for(Account a : accountArray) {
if (a != null) {
if (a.getAccountNum().equals(ano)) {
account = a;
break;
}
}
}
return account;
}
}