Java - (2주차)

이정인·2023년 7월 29일
0

JAVA

목록 보기
1/1

JAVA : ch_11 ~ 16
Spring : ch_1 ~ 2


CH_11 : 객체지향 프로그래밍

# 1. 클래스

public class BankAccount {

    // 멤버 변수
    int bankCode;       // 은행 코드
    int accountNo;      // 계좌 번호
    String owner;       // 예금주
    int balance;        // 잔액
    boolean isDormant;  // 휴면유저인지
    int password;       // 계좌 비밀번호
    // 초기 값을 설정해 주지 않으면
    // int 는 0으로,
    // boolean 은 false 로 초기화된다.

    // 메소드
    void inquiry() {}
    void deposit() {}   // 예금
    void withdraw() {}  // 출금
    void heldInDormant() {}

    // 생성자
    // 클래스 내부에 정의, 생성자 메서드명은 클래스명과 일치!
    // new 연산자와 함께 사용

    BankAccount() {
        // 기본 생성자
        // 클래스 내부에 생성자가 존재할 경우 자동으로 만들어지지 않음 주의 !
    }

    BankAccount(
            int bankCode,
            int accountNo,
            String owner,
            int balance,
            int password,
            boolean isDormant
    ) {
        // 멤버 변수      사용자로부터 입력받은 값
        this.bankCode = bankCode;
        this.accountNo = accountNo;
        this.owner = owner;
        this.balance = balance;
        this.password = password;
        this.isDormant = isDormant;

    }

}
public class ClassExample {

    public static void main(String[] args) {

        BankAccount account = new BankAccount();

    }

}

# 2. 상속

  • JAVA 는 하나의 클래스만 상속 가능하다. (단일 상속)
public class SavingsAccount extends BankAccount {

    boolean isOverdraft;    // 마이너스 통장인가?
    void transfer() {};     // 송금

}
public class DollarAccount extends BankAccount {

    // 오버로딩
    // 부모 클래스에서 상속 받은 메서드에서 파라미터를 변경
    // 새로운 메서드 정의 하는 것
    // 파라미터 변경

    void inquiry(double currencyRate) {}

    // --------------------

    // 오버라이딩
    // 부모 클래스에서 상속받은 메서드의 내용 변경
    // 자식 클래스의 상황에 맞게
    // 내용 재정의, 파라미터 그대로임

    void deposit() {

    }

}

public class SubscriptionAccount extends BankAccount {

    int numOfSubscription;

}

# 3. 접근 제어자

  • 멤버 변수에 바로 접근을 하지 못하도록 private 으로 설정
	private int bankCode;       // 은행 코드
    private int accountNo;      // 계좌 번호
    private String owner;       // 예금주
    private int balance;        // 잔액
    private boolean isDormant;  // 휴면유저인지
    private int password;       // 계좌 비밀번호
  • 메서드는 public 으로 외부에서도 접근 가능하도록 설정함.
  • 멤버 변수의 값을 직접적으로 바꿀 수 없기 때문에 멤버 변수의 값을 바꿀 수 있는 메서드를 만들어 두는 것이 일반적임.
    public void inquiry() {}
    public void deposit() {}   // 예금
    public void withdraw() {}  // 출금
    public void heldInDormant() {}
    public void changePassword(int password) {
        this.password = password;
    }
  • 마우스 우클릭 > Generate > Getter Setter

# 4. 인터페이스

  • 실제적인 구현은 하지 않음

public interface Withdrawable {

    void withdraw();

}
public class SavingsAccount extends BankAccount implements Withdrawable {

    boolean isOverdraft;    // 마이너스 통장인가?
    void transfer() {};     // 송금
    public void withdraw() {

        System.out.println("Withdraw");

    };

}

CH_12 : 예외 처리

import java.util.ArrayList;

public class ExceptionExample {

    public static void main(String[] args) {

        // 예외 (Exceptions)

        int a = 10;
        int b = 0;

        int c = a / b;
        // 0 으로 나눌 수 없다. -> 예외 : ArithmeticException
        // / by zero

        ArrayList arrayList = new ArrayList(3);
        arrayList.get(10);
        // length 를 3 으로 설정했는데 존재하지 않는 index 10 을 찾음
        // -> 오류 : IndexOutOfBoundsException
        // Index 10 out of bounds for length 0

        try {

            arrayList.get(10);
            // Error 가 발생할 수 있는 코드 작성

        } catch (
                //Exception e
                IndexOutOfBoundsException ioe
                ) {

            // catch 문의 소괄호 () 안에 있는 에러가 발생했을 시
            // 실행할 코드
            // catch 는 다중으로 사용할 수 있음

            // e.printStackTrace();
            // 에러 메시지를 출력하는 코드

            //System.out.println("에러발생");
            System.out.println("IndexOutOfBoundException 발생");

        } catch(IllegalArgumentException iae) {

            System.out.println("IllegalArgumentException 발생");

        } catch (Exception e) {

            System.out.println("Exception 발생");
            // 가장 마지막 catch 문은 가장 상위 예외 처리 넣어주는 것이 좋음

        } finally {

            System.out.println("finally");
            // 무조건 실행할 코드

        }

    }

}

CH_14 : Spring Boot 의 구조 및 작동 원리

  • 하단의 Generate 버튼 클릭해 압축된 파일 다운로드

  • 다운로드가 완료되면 압축풀기

  • intelliJ 에서 프로젝트 open

  • .gradle 파일 open

  • 참고 : https://while1.tistory.com/104

  • spring 어플리케이션 작동 하는 곳
    -> http://localhost:8080/


CH_15 : Spring Boot 데이터베이스 연동 및 CRUD API 구현

profile
둉이닝

1개의 댓글

comment-user-thumbnail
2023년 7월 29일

유익한 글이었습니다.

답글 달기