ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 왜 개체지향을 할까? - 예제
    JAVA/개념 - 김영한 강의 2024. 8. 11. 09:16

     

    절차지향 직사각형 프로그램 만들기

     

     

     

     

    이걸 객체지향으로 바꾸면,

     

    • 일단 먼저, 인스턴스와  기본 메서드를 분리해줬다

     

     

     

    • rectangle 객체 생성
    • calculateArea, calculatePerimeter, square의 자세한 로직을 알지 않아도 됨(추상화)

     

     

     

    객체 지향 은행 계좌 만들기

    • Account 클래스 만들기
      • int balance 잔액
      • deposit(int amount): 입금 메서드
        • 입금시 잔액이 증가한다
      • withdraw(int amount) : 출금 메서드
        • 출금시 잔액이 감소한다
        • 만약 잔액이 부족하면 잔액 부족을 출력해야 한다
      • AccountMain 클래스를 만들고 main() 메서드를 통해 프로그램 시작하기
        • 계좌에 만원입금 -> 9천원 출금 -> 2천원 출금 -> 잔액 부족 출력 -> 잔고 출력

     

     

    1) 일단 Account 클래스에 잔액 인스턴스를 생성했다

    class Account{
    	int balance; //잔액
        }

     

     

    2) deposit 메서드 생성하기 (입금 시 잔액이 증가한다)

    int deposit(int amount) {
    	balance += amount;
        
        return amount;
        }

     

    • deposit() 메서드는 반환 타입이 int이므로, return 문이 있어야 한다.
    • deposit() 메서드가 amount라는 매개변수를 받아야 메서드 내에서 amount라는 변수를 사용할 수 있다.

     

    근데 이걸 깔끔하게 바꾸면, 

    void deposit(int amount) {
    	balance += amount;
    }

     

     

    3) withdraw 출금 메서드(출금 시 잔액이 감소, 잔액이 부족하면 '잔액 부족' 출력)

    void withdraw(int amount) {
    	balance -= amount;
        if(balance<amount) {
        	System.out.println("잔액 부족");
        }
    }

     

    이렇게 하면 안되고^^ 

    void withdraw(int amount) {
    	if (balance >= amount) {
        	balance -= amount;
        } else {
        	System.out.println("잔액 부족");
        }
      }
    }

     

     

    Account 클래스 전체 정리

    class Account {
    	 int balance; // 잔액
     	 void deposit(int amount) {
    	 balance += amount;
     }
     	void withdraw(int amount) {
    		  if (balance >= amount) {
     		  balance -= amount;
     		 } else {
     		 System.out.println("잔액 부족");
     		}
    	 }
    }

     

    4) AccountMain 클래스를 만들고 main() 메서드를 통해 프로그램 시작하기

    public class AccountMain {
    
    	public static void main(String[] args) {
        		Account account = new Account(); // 객체생성
           			 account.deposit(10000);
           		 	account.withdraw(9000);
            		account.withdraw(2000);
           			
                System.out.println("잔고: " + account.balance);
       }
    }

     

     

     


    참고: 김영한의 실전 자바-기본편, 인프런

    'JAVA > 개념 - 김영한 강의' 카테고리의 다른 글

    접근제어자 / 캡슐화  (0) 2024.08.30
    생성자 -오버로딩(Overloading)과 this() + 오버라이딩(Overriding)  (0) 2024.08.25
    생성자  (0) 2024.08.24
    기본형과 참조형  (0) 2024.08.13
    왜 객체지향을 할까?  (0) 2024.08.11

    댓글

Designed by Tistory.