Back-End

[JAVA] 기초 공부 8(객체지향)

Minch13r 2025. 1. 10. 10:35

2025.1.10 자바 객체지향에 대한 공부 시작

 

JAVA는 객체지향 언어이다. 즉 객체지향프로그랭(OOP)라고 한다.

 

절차지향적 프로그래밍은

1~100 홀수

1~100 총합

3명의 학생이 1등을 하는 결과가 나온다.

 

객체지향 프로그래밍은

학생 따로, 자동차 따로, 포켓몬 따로 코딩이 가능하다.

 

객체지향언어의 4가지 특징

 

1. 캡슐화(Encapsulation) 

정보은닉(hiding 하고 주고받기 가능)

1) 새로운 것을 개발할 때 기존의 것을 활용 가능.

       → 기존의 것이 어떤 기능을 하는지만 알면 됨(성분 분석 필요X, 알면 좋음)

2) 개발이후 이슈가 발생했을 때, 접합부분만 검사하면 됨

       → 개발 시간, 비용 단축 → 유지보수용이

ex) 콧물용 약, 목감기용 약 이렇게 두개만 따로 떼어와서 내 증상에 맞는 콧물 + 목감기용 약으로 사용이 가능하다.

 

2. 상속(Inheritance)

계산기를 만들고 공학용계산기를 만들려고 할 때, 계산기를 똑같이 Ctrl C + V를 하면 안되니 계산기에다가 조금 기능을 추가해서 공학용계산기로 만들자는게 상속. 기존에 개발완료된 코드를 새로 개발하는 코드에 전부 가져올 수 있음.

 

3. 다형성(Polymorphism) ★

함수(메서드)를 수앵하는 주체(주어, 대상)가 어떤 객체냐 인지에 따라 다른 수행 결과가 나올 수 있다.

ex) add() → 절차지향언어에서는 함수 수행결과를 바꿀 수 없음

강아지.울음() → 멍멍 / 고양이.울음() → 야옹  ===> 객체지향언어에서는 메서드 수행결과가 다를 수 있다.

 

4. 추상화(Abstraction)

객체들의 공통되는 특징을 코딩할 수 있다!(객체들의 설계를 제공할 수 있다!)

ex) 롤에서 챔피언은 모두 q() w() e() r() 이 있는데 모두 스킬이 다르다.

챔피언.q() 챔피언.w() 챔피언.e() 챔피언. r()

포켓몬.인사() -> 피카츄는 피카피카, 꼬북이는 꼬북꼬북

주민.도구.A()

이런것들을 대략적으로 설계하면서 코딩이 가능하다. 이게 바로 추상화

 

정리 : 객체지향언어란? → "메서드에게 주어(주체)가 생기는 것이다."


package day009.class03;

class Student{
    String name;
    int score;
}

public class Test01 {
    public static void main(String[] args) {
        // 학생 1명 생성
        Student stu = new Student();
        // new 연산자
        // Student() 생성자 : 클래스와 이름이 동일한 함수
        // 객체 생성 == 객체화(인스턴스화)
        // 통칭은 Object가 맞는데 피카츄, 럭스 이런 실제 애들은 instance라고 함

        // 1명에게 이름, 성적을 부여
        stu.name = "홍길동";
        stu.score = 98;

        // 화면에 출력
        System.out.println(stu.name + " 학생은 " + stu.score + "점 입니다.");
    }
}

 


Student()를 함수라고 했는데 public static void Student()를 안 했는데도 어떻게 쓸까?

 

인자가 없는 생성자 == 기본 생성자(Default 생성자)

Student()라는 함수는 원래 없는 거지만 Student stu = new Student()는 자바에서 기본으로 제공하는 함수 생성 방식임.

생성자는 수행결과 객체를 무조건 반환 → output 기입 X
함수의 3요소가 만족된다.

package day009.class04;

    class Pokemon{ // 1. class는 기본단위
    String name; // 2. 자료형
    String type;
    int level; // 4. 멤버변수(파란색 글씨)

    Pokemon(){ // 6. 생성자의 역할 == 멤버변수 초기화
        this.name="피카츄"; // 7. 클래스명과 이름이 동일해야 함
        // class에서 만든 변수와 동일해야 한다는 것
        this.type="전기";
        this.level=5; // 8. this == 자기자신객체
        // 길동이가 길동이 책을 갖고 왔다는 어색
        // 내가 내 책을 갖고 왔다. 할 때 '내'를 가르킨다.
        // 이름 충돌 방지.
        System.out.println("기본생성자 호출");
    }

    // 생성자의 특징은 new를 선언할때마다 생성된다.
    // 9. 기본 생성자는 다른 생성자가 한개라도 작성되면 즉시 제공 XXX
        // 자바에서는 디폴트 생성자를 자동으로 생성해주는데 다른 생성자가 만들어지면 제공 안 한 다는 뜻
    Pokemon(String name, String type){
        this.name=name;
        this.type=type;
        this.level=5;
        System.out.println("생성차 호출");
    }
    // 10. 생성자 오버로딩
        // 오버로딩을 하면 기본 생성자를 못 쓰게 된다.
        // 생성자 오버로딩을 하는 이유는 객체를 다양한 방식으로 생성하기 위해서다.
        // 피자를 예시로 들었을 때 치즈만 든 치즈 피자, 치즈와 토핑이 든 피자
        // 사이즈를 선택하는 피자 등 다양하기 때문에 생성자 오버로딩을 한다.
}

public class Test01 {
    public static void main(String[] args) {
        Pokemon pika = new Pokemon();
        Pokemon pai = new Pokemon("파이리", "불꽃");
        // 3. 객체화(인스턴스화) → 생성자 함수
        // 설계도를 갖고 실제 물건(객체)를 만드는 것
        // 항상 new 키워드를 사용하고 객체화 시 반드시 생성자는 호출된다.
        // 하나의 클래스로 여러 객체를 만들 수 있고 각 객체는 독립적인 메모리 공간을 갖는다.
        // 5. pika == 객체 == 붕어빵
    }
}

 

★ 오버로딩 할 때 기본 생성자를 못 쓰게 되기 때문에 인자를 넣어 사용해야 한다. ★


package day009.class06;
/*     2) 책 객체들을 저장하고 싶습니다.
       책이란, 제목과 작가로 구성되어있습니다.
       만약, 작가를 알 수 없는 책이라면 작가의 이름을 작자미상으로 설정해주세요
*/
class Book { // 클래스
    String title; // 제목
    String writer; // 작가
    Book(String title){ // 작자미상 오버로딩
        this.title = title;
        this.writer = "작자미상";
    }

    Book(String title, String writer){ // 기본 생성자
        this.title = title;
        this.writer = writer;
    }

    void printBookInfo(){
        System.out.println(this.title + " " + this.writer); // this 쓰는게 내꺼 보여달라고 하는거
        // 여기에  book01이나 book02 들어갔을 때 자기꺼 보여줌
    }
}

public class Test02 {
    public static void main(String[] args) {
        Book book01 = new Book("해리포터", "JK톨링");
        Book book02 = new Book("춘향전");

        book01.printBookInfo();
        book02.printBookInfo();
//        System.out.println(book01.title+" "+book01.writer);
//        System.out.println(book02.title+" "+book02.writer);
    }
}
package day009.class06;
/*     2) 책 객체들을 저장하고 싶습니다.
       책이란, 제목과 작가로 구성되어있습니다.
       만약, 작가를 알 수 없는 책이라면 작가의 이름을 작자미상으로 설정해주세요
*/
class Book { // 클래스
    String title; // 제목
    String writer; // 작가
    Book(String title){ // 작자미상 오버로딩
        this.title = title;
        this.writer = "작자미상";
    }

    Book(String title, String writer){ // 기본 생성자
        this.title = title;
        this.writer = writer;
    }

    void printBookInfo(){
        System.out.println(this.title + " " + this.writer); // this 쓰는게 내꺼 보여달라고 하는거
        // 여기에  book01이나 book02 들어갔을 때 자기꺼 보여줌
    }
}

public class Test02 {
    public static void main(String[] args) {
        Book book01 = new Book("해리포터", "JK톨링");
        Book book02 = new Book("춘향전");

        book01.printBookInfo();
        book02.printBookInfo();
//        System.out.println(book01.title+" "+book01.writer);
//        System.out.println(book02.title+" "+book02.writer);
    }
}
package day009.class06;
/*3) 상품 객체들을 다룰 예정입니다.
       상품은 이름, 가격, 재고가 있습니다.
       만약 재고를 설정하지 않으면 0개가 기본설정되도록 해주세요.
*/
class Object{ // 상품 클래스
    String name; // 이름
    int price; // 가격
    int cnt; // 재고
    Object(String name, int price, int cnt){
        this.name = name;
        this.price = price;
        this.cnt = cnt;
    }
    Object(String name, int price){ // 재고의 개수를 입력하지 않는 경우
        this.name = name;
        this.price = price;
        this.cnt = 0; // 0개가 기본설정
    }
}
public class Test03 {
    public static void main(String[] args) {
        Object object01 = new Object("홍삼", 10500, 5);
        Object object02 = new Object("치킨", 5000);

        System.out.println(object01.name + "의 가격은 " + object01.price + "원 입니다. 재고의 개수는 " + object01.cnt + "개 입니다.");
        System.out.println(object02.name + "의 가격은 " + object02.price + "원 입니다. 재고의 개수는 " + object02.cnt + "개 입니다.");
    }
}
package day009.class06;
/*     자동차 클래스를 구현해주세요.
       자동차는 현재 속도를 보여줄 수 있고,
       모든 자동차들은 최대 속도가 120을 넘길 수 없습니다.*/
class Car {
    // 120 넘을 수 있어, 근데 120 넘게 받으면 내보내는거는 120 내보내라는거
    // 그 어떤 수를 입력해도 최대 속도를 넘으면 120만 내보내기
    int speed;
    int maxspeed;
    Car(int speed){
        this.speed = speed;
        this.maxspeed = 120;

        if(this.speed > this.maxspeed){
            this.speed = this.maxspeed;
            System.out.println("모든 자동차들은 최대 속도가 " + this.maxspeed + "을 넘을 수 없습니다.");
        }
    }
}
public class Test04 {
}

코드 피드백

package day008;

import java.util.Random;
import java.util.Scanner;

public class ViewNModelAssignment {
    public static int[] stuList = {10, 20, 0};

    public static int[] selectAll() {
        return stuList;
    }
    public static int selectOne(int num) {
        if(num<=0 || stuList.length<num) {
            return 0;
        }
        return stuList[num-1];
    }

    // model 함수가 다 짜져있다는 가정 하에 View 진행
    public static void printMenu() { // 메뉴 보여주는 함수
        System.out.println("===== 학생부 프로그램 =====");
        System.out.println("1. 전체출력");
        System.out.println("2. 1등 출력");
        System.out.println("3. 정보추가");
        System.out.println("4. 정보변경");
        System.out.println("0. 프로그램 종료");
        System.out.println("========================");
    }

    public static void printNum() {
    }

    // 학생이 존재하는 지 검사하는 함수
    public static boolean isStu(int cnt) {
        boolean flag = false; // 학생이 존재한다는 가정

        if(cnt <= 0) {
            flag = true;
            System.out.println("출력할 데이터가 없습니다");
        }

        return false;
    }

    // 전체출력
    public static void printList(int cnt) {
        for(int i=0; i<cnt; i++) {
            System.out.println((i+1) + "번 학생의 점수 : " + stuList[i] + "점");
        }
        System.out.println();
    }

    public static int inputAction() { // 메뉴 번호 입력 함수
        Scanner sc = new Scanner(System.in);

        int action;
        while(true) {
            System.out.print(">> ");
            action = sc.nextInt();

            if(0<=action && action<=4) {
                break;
            }

            System.out.println("옳지 않은 숫자 범위입니다!");
        }

        return action;
    }

    // 1등 출력
    public static void printTop(int maxIndex, int max) {
        System.out.println("1등은 " + (maxIndex + 1) + "번 학생, " + max + "점 입니다.");
    }

    // 점수 입력
    public static int inputScore() {
        Scanner sc = new Scanner(System.in);

        int score;
        while(true) {
            System.out.print("추가할 학생의 점수 입력 : ");
            score = sc.nextInt();
            if(score >= 0 && score <= 100) {
                break;
            }
            System.out.println("0~100점 사이만 입력 가능합니다!");
        }
        return score;
    }

    // 학생 추가
    public static void addStudent(int score) {
        System.out.println(score+"점 입력\n학생 정보 추가 완료!");
    }

    // 학생 허용치 초과 검사 함수
    public static boolean isLenFull(int cnt) {
        boolean flag = false;//깃발 변수 - 비초과상태 가정

        if(cnt >= selectAll().length) {
            flag = true;
            System.out.println("최대 학생 수입니다!");
        }

        return flag;
    }

    // 정보변경할 학생 번호 입력 함수
    public static int inputStudentNumber(int cnt) {
        Scanner sc = new Scanner(System.in);

        int num;
        while(true) {
            System.out.print("정보변경할 학생의 번호 입력 : ");
            num = sc.nextInt();
            if(num >= 1 && num <= cnt) {
                break;
            }
            System.out.println("해당 번호의 학생은 존재하지 않습니다!");
        }
        return num;
    }

    public static void printChangeScore(int num, int score) {
        System.out.println(num+"번 학생의 점수가 "+score+"점으로 변경되었습니다.");
    }

    public static void printExit(){
        System.out.println("프로그램을 종료합니다");
    }

    // 학생 랜덤 점수 저장하는 함수
    public static int modifyScore(int num) {
        Random rand = new Random();

        int ranScore;
        while(true) {
            ranScore = rand.nextInt(101); // 랜덤값 저장 변수

            if(selectOne(num) != ranScore) {
                break;
            }
        }

        return ranScore;
    }


    public static void main(String[] args) {
        int cnt = 0;

        while(true){
            printMenu();

            int action = inputAction(); // 입력 함수 호출

            if(action == 0) { // 종료조건
                printExit();
                break;
            }
            else if(action == 1) { // 전체 출력
                if(isStu(cnt)) { // UI/UX + if-else보다 continue가 뎁스를 줄이기 때문에 좋아한다.
                    continue;
                }

                printList(cnt);
            }
            else if(action == 2) { // 1등 점수 출력
                if(isStu(cnt)) { // UI/UX + if-else보다 continue가 뎁스를 줄이기 때문에 좋아한다.
                    continue;
                }

                // 학생부 배열에서 점수가 가장 큰 학생을 찾아서
                //   ---> 최댓값 찾기 알고리즘
                int max = stuList[0];
                int maxIndex = 0;

                for(int i=1; i<cnt; i++) {
                    if(max<stuList[i]) {
                        max = stuList[i];
                        maxIndex = i;
                    }
                }
                if(cnt > 0 && cnt <=3){
                printTop(maxIndex, max);
                }
            }
            else if(action == 3) { // 정보 추가
                if(isLenFull(cnt)) {
                    continue;
                }

                int score = inputScore();

                // 입력받은 점수 정보를 배열에 저장
                stuList[cnt++]= score;

                addStudent(score);
            }
            else if(action == 4) { // 정보 변경
                if(isStu(cnt)) { // UI/UX + if-else보다 continue가 뎁스를 줄이기 때문에 좋아한다.
                    continue;
                }

                printList(cnt);

                // 변경할 학생 번호 입력받기
                int num = inputStudentNumber(cnt);

                // 랜덤으로 점수값 저장
                int score = modifyScore(num);

                // 랜덤값으로 변경
                selectAll()[num-1] = score;

                printChangeScore(num, score);
            }


        }
    }

}

 

일단 필요없거나 의미 없는 함수들은 한 번 싹 정리를 해준다. 그리고 여기에는 ViewNModelAssignment라고 나와있지만 원래는 Test01이라는 이름으로 저장되어 있었다. 이런 경우에는 이름을 어떤 파일인지 명확히 알려주는 그런 이름으로 하는게 좋다.

랜덤값으로 변경할 때 selectAll()[num-1]로 작성했는데 model은 이런식으로 동작하지 않는다. 우리가 현재 배열의 크기와 내용을 알고 있어 이런 실수를 범한 것 같다. model은 데이터베이스 안에 어떤 값이 있는지 궁금하지 않다. 주소만 알고 주소를 갖고 와서 보여주는게 View다. 갖고오는 과정은 Model. 그니까 쉽게 말하자면 Model은 강남구 테헤란로라는 주소를 가지고 와서 대입하는거고 View는 그 주소에 구글코리아가 있다는거를 보여주는 작업인거다. 그 요청은 Controller가 하는거고 이런식이다.

'Back-End' 카테고리의 다른 글

[JAVA] 기초 공부 9  (1) 2025.01.14
[JAVA] 기초 공부 8  (1) 2025.01.13
[JAVA] 기초 공부 7(MVC, 오버로딩)  (1) 2025.01.09
[JAVA] 선택 정렬 함수 이용해서 코드짜기  (0) 2025.01.08
[JAVA] 기초 공부 6(함수)  (4) 2025.01.07