국비

[ 12일차 50~54 ] 수업 정리 - 자바

코딩하는냥이 2025. 4. 29. 17:15
반응형

✅ 오전 수업 요약

1. final 필드 (Korean 클래스)

  • final은 한 번 값이 설정되면 변경 불가
  • 생성자 또는 선언 시 초기화 가능

2. static final 상수 (Earth 클래스)

  • static final로 고정값(상수) 선언
  • 관례적으로 대문자로 작성
  • 클래스명으로 접근

3. 접근 제한자 (A, B, C 클래스)

  • public : 어디서나 접근 가능
  • (default) : 같은 패키지 내에서만 접근 가능
  • private : 클래스 내부에서만 접근 가능
  • 다른 패키지에서 default, private 접근 시 컴파일 에러

✅ 오후 수업 요약

1. Getter / Setter 메서드 (Car 클래스)

  • private 필드 값을 안전하게 다루기 위해 Getter/Setter 사용
  • 유효성 검사(예: 음수 속도 입력 시 보정) 포함
  • isStop() 메서드는 boolean형 필드 getter로 활용

✅ 자습 내용 요약

1. Member 클래스 생성 및 사용 (mission14)

package ch06.sec99.mission14;

public class Member {
	String name;
	String id;
	String password;
	int age;
	
	Member(String name, String id){
		this.name = name;
		this.id = id;
	}
}
package ch06.sec99.mission14;

public class MemberExample {
	public static void main(String[] args) {
		Member m1 = new Member("홍길동", "hong");
		
		System.out.println("name : " + m1.name + " / id : " + m1.id);
	}
}
  • name, id 필드 설정
  • 생성자를 통해 필드 초기화

2. MemberService 로그인 기능 (mission15)

package ch06.sec99.mission15;

public class MemberService {
	boolean login(String id, String password) {
		if (id.equals("hong") && password.equals("12345"))
			return true;
		else
			return false;
	}

	void logout(String id) {
		System.out.println(id + "님이 로그아웃 되었습니다");
	}
}
package ch06.sec99.mission15;

public class MemberServiceExample {
	public static void main(String[] args) {
		MemberService memberService = new MemberService();
		boolean result = memberService.login("hong", "12345");
		if (result) {
			System.out.println("로그인 되었습니다.");
			memberService.logout("hong");
		} else {
			System.out.println("id 또는 password가 올바르지 않습니다.");
		}
	}
}
  • 로그인 검증 메서드 login()
  • 로그아웃 메서드 logout()

3. Printer 클래스 (mission16, mission17)

  • instance 메서드 버전 (mission16)
package ch06.sec99.mission16;

public class Printer {
	void println(String value){
		System.out.println(value);
	}
	
	void println(int value) {
		System.out.println(value);
	}
	
	void println(boolean value) {
		System.out.println(value);
	}
	
	void println(double value) {
		System.out.println(value);
	}
}
package ch06.sec99.mission16;

public class PrinterExample {
	public static void main(String[] args) {
		Printer printer = new Printer();
		printer.println(10);
		printer.println(true);
		printer.println(5.7);
		printer.println("홍길동");
	}
}
  • static 메서드 버전 (mission17)
package ch06.sec99.mission17;

public class Printer {
	static void println(String value) {
		System.out.println(value);
	}

	static void println(int value) {
		System.out.println(value);
	}

	static void println(boolean value) {
		System.out.println(value);
	}

	static void println(double value) {
		System.out.println(value);
	}
}
package ch06.sec99.mission17;

public class PrinterExample {
	public static void main(String[] args) {
		Printer.println(10);
		Printer.println(true);
		Printer.println(5.7);
		Printer.println("홍길동");
	}
}
  • 다양한 타입(String, int, boolean, double) 출력 가능

4. ShopService 싱글톤 패턴 (mission18)

package ch06.sec99.mission18;

public class ShopService {
	private static ShopService singleton = new ShopService();
	private ShopService() {
	}
	
	public static ShopService getInstance() {
		return singleton;
	}
}
package ch06.sec99.mission18;

public class ShopServiceExample {
	public static void main(String[] args) {
		ShopService obj1 = ShopService.getInstance();
		ShopService obj2 = ShopService.getInstance();
		
		if(obj1 == obj2)
			System.out.println("같은 ShopService 객체입니다.");
		else
			System.out.println("다른 ShopService 객체입니다.");
	}
}
  • 객체를 단 하나만 생성하는 패턴
private static ShopService singleton = new ShopService();
private ShopService() { }
public static ShopService getInstance() { return singleton; }
  • == 비교로 동일 객체 확인

5. Account 클래스 (mission19)

package ch06.sec99.mission19;

public class Account {
	private int balance = 0;
	final private int MIN_BALANCE = 0;
	final private int MAX_BALANCE = 1000000;

	public int getBalance() {
		return balance;
	}

	public void setBalance(int balance) {
		if (MIN_BALANCE <= balance && balance <= MAX_BALANCE) {
			this.balance = balance;
		}
	}
}
package ch06.sec99.mission19;

public class AccountExample {
	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(30000);
		System.out.println("현재 잔고 : " + account.getBalance());
	}
}
  • 잔액 제한 (MIN_BALANCE, MAX_BALANCE)
  • Setter에서 유효한 범위 내일 때만 설정

6. BankApplication - 계좌 관리 프로그램 (mission20)

package ch06.sec99.mission20;

public class Account {
	private String num = null;
	private String name = null;
	private int balance = 0;
	final private int MIN_BALANCE = 0;
	final private int MAX_BALANCE = 1000000;

	public int getBalance() {
		return balance;
	}

	public void setBalance(int balance) {
		if (MIN_BALANCE <= balance && balance <= MAX_BALANCE) {
			this.balance = balance;
		}
	}
	
	public void plusBalance(int balance) {
		this.balance += balance;
	}
	
	public void minusBalance(int balance) {
		this.balance -= balance;
	}

	public String getNum() {
		return num;
	}

	public void setNum(String num) {
		this.num = num;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
	
	public static void main(String[] args) {
		
	}
}
package ch06.sec99.mission20;

import java.util.Scanner;

public class BankApplication {
	final public static int NOT_NUM = -1;
	Scanner sc = new Scanner(System.in);
	Account account[] = new Account[100];
	String input;

	public static void main(String[] args) {
		BankApplication ba = new BankApplication();
		ba.start();
		System.out.println("프로그램 종료");
	}

	void start() {
		while (true) {
			System.out.println("-".repeat(50));
			System.out.println("1.계좌생성 | 2.계좌목록 | 3.예금 | 4.출금 | 5. 종료");
			System.out.println("-".repeat(50));
			System.out.print("선택> ");

			input = sc.nextLine();
			if (input.equals("1"))
				createAccount();
			else if (input.equals("2"))
				accountList();
			else if (input.equals("3"))
				moneyPlue();
			else if (input.equals("4"))
				moneyMinus();
			else
				break;

		}
	}

	void createAccount() {
		Account acc = new Account();

		System.out.println("-".repeat(10));
		System.out.println("계좌생성");
		System.out.println("-".repeat(10));

		System.out.print("계좌번호 : ");
		input = sc.nextLine();
		acc.setNum(input);

		System.out.print("계좌주 : ");
		input = sc.nextLine();
		acc.setName(input);

		System.out.print("초기입금액 : ");
		input = sc.nextLine();
		acc.setBalance(Integer.parseInt(input));

		for (int i = 0; i < account.length; i++)
			if (account[i] == null) {
				account[i] = acc;
				break;
			}

		System.out.println("결과: 계좌가 생성되었습니다.");
	}

	void accountList() {
		System.out.println("-".repeat(10));
		System.out.println("계좌목록");
		System.out.println("-".repeat(10));

		for (int i = 0; i < account.length; i++) {
			if (account[i] == null)
				break;
			System.out.println(account[i].getNum() + "\t" + account[i].getName() + "\t" + account[i].getBalance());
		}
	}

	void moneyPlue() {
		int money;

		System.out.println("-".repeat(10));
		System.out.println("예금");
		System.out.println("-".repeat(10));

		System.out.print("계좌번호 : ");
		input = sc.nextLine();
		int i = searchAccount(input);

		if (i != NOT_NUM) {
			System.out.print("예금액 : ");
			money = Integer.parseInt(sc.nextLine());
			account[i].plusBalance(money);
		}

	}

	void moneyMinus() {
		int money;

		System.out.println("-".repeat(10));
		System.out.println("출금");
		System.out.println("-".repeat(10));

		System.out.print("계좌번호 : ");
		input = sc.nextLine();
		int i = searchAccount(input);

		if (i != NOT_NUM) {
			System.out.print("출금액 : ");
			money = Integer.parseInt(sc.nextLine());
			account[i].minusBalance(money);
			System.out.println("결과: 출금이 성공되었습니다.");
		}
	}

	int searchAccount(String input) {
		for (int i = 0; i < account.length; i++)
			if (account[i] == null)
				break;
			else if (account[i].getNum().equals(input))
				return i;
		return NOT_NUM;
	}
}
  • 기능:
    • 계좌 생성
    • 계좌 목록 출력
    • 예금
    • 출금
  • 계좌는 Account 배열에 저장
  • Scanner로 사용자 입력 받아 처리
  • 배열에 null 체크하여 빈 공간에 새 계좌 저장
  • 예금/출금 시 계좌번호 일치 여부 검사

📌 12일차 핵심 요약

항목 주요 내용
final 필드 한 번 초기화 후 값 변경 불가
static final 상수 클래스 로딩 시 고정, 대문자 명명
접근 제한자 public, default, private 차이 이해
Getter/Setter 필드 보호 및 안전한 값 조작
메서드 오버로딩 이름 같고 매개변수 다르게 여러 메서드 정의
싱글톤 패턴 하나의 인스턴스만 생성 및 공유
실습 프로젝트 계좌 관리 프로그램 구축 (생성, 목록, 예금, 출금)