[Java] SW 설계 방법론 강의 정리

eunbi·2022년 8월 14일
0

1학년 때 수강한 강의노트를 간단히 정리.

1. 간단한 자바 프로그램

MVC구조

  • 모델(model)-뷰(view)-제어기(controller) 구조
  • 뷰 : 사용자와 상호작용을 관장하는 객체
  • 제어기 : 정보를 전달하는 것을 관장하는 객체
  • 모델 : 제어기의 메시지에 따라 계산을 하는 객체

2. 산술연산과 변수

온도 변환 프로그램


public class CelsiusToFahrenheit1 {
	public static void main(String[] args) {
    	int c = new Integer(args[0]).intValue();
        double f = ((9.0/5.0)*c) + 32;
        System.out.println("For Celsius degrees " + c + ",");
        DecimalFormat formatter = new DecimalFormat("0.0");
        System.out.println("Degrees Fahrenheit = " + formatter.format(f));
	}
}

3. 부품구조 : 클래스와 메소드(1)

객체, 메소드, 필드

  • 객체(object) : 하나의 물건
  • 필드(field) : 고유 속성값, 객체들이 저장해야 할 정보들.
  • 메소드 : 해당 클래스가 할 수 있는 것들.

메모리 모델

int var1 = 52;
Location A = new Location(37.32, 126.83);
Location B = new Location(37.55, 127.04);
B.longitude = 127.05;

  • 생성자 메소드는 항상 this를 반환한다.
(1)
public class LocationTester {
	public static void main(String[] args) {
    	double lat = 37.55;
        Location seoul = new Location(37.55, 127.04);
	}
}

(2)
public class Location {
	public double lat;
    public double lon;
    public Location(double latIn, double lonIn) {
    	this.lat = latIn;
        this.lon = lonIn;
        return this;
	}
}

메소드 오버로딩 Overloading

  • 같은 이름의 메소드를 여러 개 정의하는 것. 다만 리턴타입이 동일해야 하고, 함수의 매개변수가 달라야 한다.

정적 필드 변수, 메소드 static

-> 객체 생성 없이 바로 사용 가능.

4. 제어 구조

은행 계좌 관리 프로그램

  • BankAccount (모델)
public class BankAccount {
    public String account_name;
    private int balance;

    public BankAccount(String account_name, int balance) {  // 생성자
        this.account_name = account_name;
        if (balance >= 0)
            this.balance = balance;
        else
            this.balance = 0;
    }

    public int getBalance() {   // 잔액 접근 메소드
        return balance;
    }

    public boolean deposit(int amount) { // 입금 메소드
        boolean result = false;
        if (amount < 0)
            JOptionPane.showMessageDialog(null, "잘못된 입금액입니다.");
        else {
            balance = balance + amount;
            result = true;
        }
        return result;
    }

    public boolean withdraw(int amount) { // 출금 메소드 (변경 메소드)
        boolean result = false;
        if (amount < 0)
            JOptionPane.showMessageDialog(null, "잘못된 출금액입니다.");
        else if (amount > balance)
            JOptionPane.showMessageDialog(null, "잔고가 부족합니다.");
        else {
            balance = balance - amount;
            result = true;
        }
        return result;
    }
}
  • BankReader (입력 뷰)
public class BankReader {
    private String input_line = "";

    public char readCommand(String message) {
        input_line = JOptionPane.showInputDialog(message).toUpperCase();
        return input_line.charAt(0);
    }

    public int readAmount() {
        int answer = 0;
        String s = input_line.substring(1, input_line.length());
        if (s.length() > 0) {
            double dollars_cents = new Double(s).doubleValue();
            answer = (int)(dollars_cents*100);
        }
        else
            JOptionPane.showMessageDialog(null, "금액이 입력되지 않았습니다.");
        return answer;
    }
}
  • BankWriter (출력 뷰)
public class BankWriter {
    private BankAccount bank;
    private String last_transaction = "";

    public BankWriter (BankAccount b) { bank = b; } // 생성자

    private String uncovert (int i) {   // 형식 변환
        return new DecimalFormat("0.00").format(i/100.0);
    }

    public void showTransaction (String message, int amount) { // 화면 출력 (메시지, 금액)
        last_transaction = message + " " + uncovert(amount);
        System.out.println(bank.account_name + ": " + last_transaction);
        System.out.println("Current balance = $" + uncovert(bank.getBalance()));
    }

    public void showTransaction (String message) {  // 화면 출력 (메시지)
        last_transaction = message;
        System.out.println(bank.account_name + ": " + last_transaction);
    }
}
  • AccountController (제어기)
public class AccountController {
    private BankReader reader;
    private BankWriter writer;
    private BankAccount account;

    public AccountController(BankReader r, BankWriter w, BankAccount a) {
        reader = r;
        writer = w;
        account = a;
    }

    public void processTransactions() {
        char command = reader.readCommand("명령 D/W/Q와 금액을 입력하세요.");
        switch (command) {
            case 'Q':
                return;
            case 'D': {
                int amount = reader.readAmount();
                if (account.deposit(amount)) writer.showTransaction("입금 $", amount);
                else writer.showTransaction("입금 오류 ", amount);
                break;
            }
            case 'W': {
                int amount = reader.readAmount();
                if (account.withdraw(amount)) writer.showTransaction("출금 $", amount);
                else writer.showTransaction("출금 오류 ", amount);
                break;
            }
            default:
                writer.showTransaction("잘못된 명령 " + command);
        }
        this.processTransactions();
    }
}
  • AccountManager
public class AccountManger {
    public static void main(String[] args) {
        BankReader reader = new BankReader();
        BankAccount account = new BankAccount("myaccount", 0);
        BankWriter writer = new BankWriter(account);
        AccountController controller = new AccountController(reader, writer, account);
        controller.processTransactions();
    }
}

5. 부품구조 : 클래스와 메소드(2)

접근자

  • public : 어떤 클래스에서도 접근 가능
  • protected : 자기 자신 / 같은 패키지 안의 클래스 / 자식 클래스
  • package : 자기 자신 / 같은 패키지 안의 클래스
  • private : 동일 클래스

상속 inheritance

  • B를 토대로 A를 만드는 것. (틀을 가져다 쓰는것.)
    public class A extend B {...}

  • 부모 클래스 (B), 자식 클래스 (A)

  • 상속되는 것
    - public 멤버 변수
    - public 메소드
    - Protected 접근 지정자

Is-a 관계

Object 클래스

  • 모든 클래스의 최상위 클래스 (자동으로 object가 상속됨.)

컴파일러의 타입 결정


1. 컴파일러는 실행 전에 객체의 해당 클래스(참조 타입)을 알 수 없다.
- 타입 강제 변환(casting)으로 해결.
2. is-a 관계 불일치.

상속에 관한 컴파일러 규칙

  1. 상위 클래스를 지정하지 않으면, object 클래스를 자동 상속한다.
  2. 생성자를 만들지 않으면, 자바가 기본 생성자를 만들어 사용한다.
  3. 생성자 메소드의 첫번째 라인엔 항상 동일 클래스의 생성자 메소드를 호출하거나 / 부모 클래스의 생성자 메소드를 호출한다. 또는 super() 를 자동 호출한다.
  • 예시)
public class Person {
	private String name;
    public Person (String n) {
    	super();
        this.name = n;
   	}
}
-----------------------------------------
public class Student extends Person {
	public Student() {
    	this.setName("Student");
	}
}
  • 생성자가 있으므로, 자바는 기본 생성자를 만들지 않는다. - (2)
  • 아래 클래스의 생성자에선 super(), person()을 호출하지만, - (3)
    해당하는 생성자가 없으므로 이를 찾지 못 하는 에러가 발생한다.

클래스 생성 시 일어나는 일

메소드 재정의 overriding

  • 하위 클래스가 상속 받을 때, 메소드를 재정의할 수 있음.
오버로딩오버라이딩
메소드 이름동일동일
매개변수, 타입다름동일

6. 부품구조 : 인터페이스, 추상 클래스

인터페이스

interface B
class A implements B

  • 클래스 (A)

  • 인터페이스 (B) : 모든 필드, 메소드를 타입에 맞게 제공한다.

  • 클래스 / 객체 / 인터페이스 / 상속 / 구현

    • 로봇의 주요기능(걷기, 장애물 피하기) : 인터페이스
    • 로봇 제작 설명서 : 클래스
    • 설명서로 만든 로봇들 : 객체들
    • 설명서로 만든 로봇들이지만, 기능을 추가한 것(+손 올리기) : 상속

하위 타입 subtype

  • 타입 : 값의 집합, 값의 포함관계로 상하위 관계를 가짐.
  • 상속, 인터페이스 구현 → 하위타입
    class B extends A
    class B implements A
    B(하위) < A(상위)
    예시 ) A : 생물, B : 사람 => 생물은 죽는다 → 사람은 죽는다
  • 하위타입 변수에 상위타입 객체 는 불가능! (is-a관계)
    B = new A. -> A is a B = 생물은 사람이다 (X)

추상 클래스 Abstract Class

abstract class A
  • 구현이 덜 된 클래스 (메소드 중 일부가 정의되지 않는 클래스)
  • 메소드 구현을 공유하기 때문에 인터페이스보다 유리하다.
    - 코드 재사용 : 메소드 중 일부를 동일하게 사용.
    • 인터페이스 만족 : 메소드 중 일부를 반드시 구현.

0개의 댓글