본문 바로가기
TIL/JAVA

23.05.04

by J1-H00N 2023. 5. 4.

 

package nadocoding.Chap_07;

public class BlackBox {
    // _02
    String modelName; // 모델명
    String resolution; // 해상도
    int price; // 가격
    String color; // 색상
    int serialNumber; // 시리얼 번호

    static int counter = 0; // 시리얼 번호를 생성해주는 역할 (처음엔 0이였다가 증감연산자로 증가)
    // _03
    static boolean canAutoReport = false; // 자동 신고 가능

    // _08
    BlackBox() {  // 생성자 // 인스턴스가 생성될 때 자동으로 실행되는 메소드
//        System.out.println("기본 생성자 호출");
//        this.serialNumber = ++counter;
//        System.out.println("새로운 시리얼 넘버를 발급받았습니다. " + this.serialNumber);
    }

    BlackBox(String modelName, String resolution, int price, String color) {
//        this(); // 기본 생성자 호출
//
//        System.out.println("사용자 지정 생성자 호출");
//        this.modelName = modelName;
//        this.resolution = resolution;
//        this.price = price;
//        this.color = color;
    }

    // _04
    void autoReport() {
        if (canAutoReport) {
            System.out.println("충돌이 감지되어 자동으로 신고합니다.");
        } else {
            System.out.println("자동 신고 기능이 지원되지 않습니다.");
        }
    }

    void insertMemoryCard(int capacity) {
        System.out.println("메모리 카드가 삽입되었습니다.");
        System.out.println("용량은 " + capacity + "GB 입니다.");
    }

    int getVideoFileCount(int type) {
        if (type == 1) {
            return 9;
        } else if (type == 2) {
            return 1;
        } else {
            return 10;
        }
    }

    void record(boolean showDateTime, boolean showSpeed, int min) {
        System.out.println("녹화를 시작합니다.");
        if (showDateTime) {
            System.out.println("영상의 날짜정보가 표시됩니다.");
        }
        if (showSpeed) {
            System.out.println("영상의 속도정보가 표시됩니다.");
        }
        System.out.println("영상은 " + min + "분 단위로 기록됩니다.");
    }

    //_05
    void record() {
        record(true, true, 5);
    }

    // _06
    static void callServiceCenter() {
        System.out.println("서비스 센터(1588-0000) 로 연결합니다.");
        // modelname = "test"; // 클래스 메소드 내에서는 인스턴스 변수 사용 불가능
        // canAutoReport = false; // 클래스 변수만 사용 가능
    }

    // _07
    void appendModelName(String modelName) {
        // modelName += modelName; // 이렇게 하면 전달값에 전달값을 더하는 기능이 되버린다.
        // 이와같이 이미 존재하는 인스턴스 변수명과 전달값의 이름이 같은 경우 이를 구분하기 위해 this를 붙인다.
        this.modelName += modelName;
    }

    // _09
    // Getter & Setter
    String getModelName() {
        return modelName;
    }

    void setModelName(String modelName) {
        this.modelName = modelName;
    }

    String getResolution() {
        if (resolution == null || resolution.isEmpty()) {
            return "판매자에게 문의하세요.";
        }
        return resolution;
    }

    void setResolution(String resolution) {
        this.resolution = resolution;
    }

    int getPrice() {
        return price;
    }

    void setPrice(int i) {
        if (price < 100000) {
            this.price = 100000;
        } else {
            this.price = price;
        }
    }

    String getColor() {
        return color;
    }

    void setColor(String color) {
        this.color = color;
    }
}

 

package nadocoding.Chap_07;

public class _01_Class {
    public static void main(String[] args) {
        // 객체 지향 프로그래밍 (OOP : Objected-Oriented Programing)
        // 유지 보수 용이
        // 높은 재사용성

        // 차량용 블랙박스
        // 모델명, 해상도, 가격, 색상
        String modelName = "까망이";
        String resolution = "FHD";
        int price = 200000;
        String color = "블랙";

        // 새로운 제품을 개발
        String modelName2 = "하양이";
        String resolution2 = "UHD";
        int price2 = 300000;
        String color2 = "화이트";

        // 또다른 제품을 개발?
        BlackBox bbox = new BlackBox();
        // BlackBox 클래스로부터 bbox 객체 생성
        // bbox 객체는 BlackBox 클래스의 인스턴스

        BlackBox bbox2 = new BlackBox();
    }
}

 

package nadocoding.Chap_07;

public class _02_InstanceVariables {
    public static void main(String[] args) {
        // 처음 만든 블랙박스 제품
        BlackBox b1 = new BlackBox();
        b1.modelName = "까망이";
        b1.resolution = "FHD";
        b1.price = 200000;
        b1.color = "블랙";

        System.out.println(b1.modelName);
        System.out.println(b1.resolution);
        System.out.println(b1.price);
        System.out.println(b1.color);

        System.out.println("-----------------");

        // 새로운 블랙박스 제품
        BlackBox b2 = new BlackBox();
        b2.modelName = "하양이";
        b2.resolution = "UHD";
        b2.price = 300000;
        b2.color = "화이트";

        System.out.println(b2.modelName);
        System.out.println(b2.resolution);
        System.out.println(b2.price);
        System.out.println(b2.color);
    }
}

 

package nadocoding.Chap_07;

public class _03_ClassVariables {
    public static void main(String[] args) {
        BlackBox b1 = new BlackBox();
        b1.modelName ="까망이";
        System.out.println(b1.modelName);

        BlackBox b2 = new BlackBox();
        b2.modelName = "하양이";
        System.out.println(b2.modelName);

        // 특정 범위를 초과하는 출동 감지 시 자동 신고 기능 개발 여부
        System.out.println(" - 개발 전 -");
        System.out.println(b1.modelName + " 자동 신고 기능 : " + b1.canAutoReport);
        System.out.println(b2.modelName + " 자동 신고 기능 : " + b2.canAutoReport); // 인스턴스로 클래스 변수 접근 지양
        System.out.println("모든 블랙박스 제품 자동 신고 기능 : " + BlackBox.canAutoReport); // 클래스 변수는 클래스 명으로 접근

        // 기능 개발
        BlackBox.canAutoReport = true;
        System.out.println(" - 개발 후 -");
        System.out.println(b1.modelName + " 자동 신고 기능 : " + b1.canAutoReport);
        System.out.println(b2.modelName + " 자동 신고 기능 : " + b2.canAutoReport);
        System.out.println("모든 블랙박스 제품 자동 신고 기능 : " + BlackBox.canAutoReport);
    }
}

 

package nadocoding.Chap_07;

public class _04_Method {
    public static void main(String[] args) {
        BlackBox b1 = new BlackBox();
        b1.modelName = "까망이";

        b1.autoReport(); // 지원 안됨
        BlackBox.canAutoReport = true;
        b1.autoReport(); // 지원 됨

        b1.insertMemoryCard(256);

        // 일반 영상 : 1
        // 이벤트 영상 (충돌 감지) : 2
        int fileCount = b1.getVideoFileCount(1); // 일반 영상
        System.out.println("일반 영상 파일 수 : " + fileCount + "개");

        fileCount = b1.getVideoFileCount(2); // 이벤트 영상
        System.out.println("이벤트 영상 파일 수 : " + fileCount + "개");
    }
}

 

package nadocoding.Chap_07;

public class _05_MethodOverloading {
    public static void main(String[] args) {
        BlackBox b1 = new BlackBox();
        b1.modelName = "까망이";

        b1.record(false, false, 10);
        System.out.println("---------------");
        b1.record(true, false, 3);
        System.out.println("---------------");
        b1.record();

        // String
        String s = "BlackBox";
        System.out.println(s.indexOf("a")); // indexOf를 ctrl + 클릭 시 indexOf 메소드를 확인할 수 있음.
    }
}

 

package nadocoding.Chap_07;

public class _06_ClassMethod {
    public static void main(String[] args) {
//        BlackBox b1 = new BlackBox();
//        b1.callServiceCenter();
//
//        BlackBox b2 = new BlackBox();
//        b2.callServiceCenter();

        BlackBox.callServiceCenter(); // 클래스 변수와 마찬가지로 클래스 메소드도 클래스 명으로 접근

        // 객체마다 다른 값을 받아 다른 결과가 나올 수 있는 경우는 인스턴스 메소드, 그 외에는 클래스 메소드를 고려한다.
    }
}

this

package nadocoding.Chap_07;

public class _07_This {
    public static void main(String[] args) {
        BlackBox b1 = new BlackBox();
        b1.modelName = "까망이"; // 까망이(최신형)
        b1.appendModelName("(최신형)"); // 만족하는 메소드가 없는 상황에서 이름만 만들면 intellij에서는 클래스 내에 메서드를 만들 수 있도록 경고를 준다.
        // 메소드 ctrl + 클릭시 메소드가 있는 곳으로 이동, ctrl + shift + i 시 바로 코드를 볼 수 있다.
        System.out.println(b1.modelName);
    }
}

 

package nadocoding.Chap_07;

public class _08_Constructor {
    public static void main(String[] args) {
        BlackBox b1 = new BlackBox(); // 기본 생성자 호출
        b1.modelName = "까망이";
        b1.resolution = "FHD";
        b1.price = 200000;
        b1.color = "블랙";
        System.out.println(b1.modelName);
        System.out.println(b1.serialNumber);

        System.out.println("---------------------");

        BlackBox b2 = new BlackBox("하양이", "UHD", 300000, "화이트");
        System.out.println(b2.modelName);
        System.out.println(b2.serialNumber);
    }
}

 

package nadocoding.Chap_07;

import com.sun.xml.internal.ws.addressing.WsaActionUtil;

public class _09_GetterSetter {
    public static void main(String[] args) {
        BlackBox b1 = new BlackBox();
        b1.modelName = "까망이";
        // b1.resolution = "FHD";
        b1.price = 200000;
        b1.color = "블랙";

        // 할인 행사 // -=을 = -로 잘못 쓴 경우
        b1.price = -5000;
        System.out.println("가격 : " + b1.price + "원");

        // 고객 문의 // resolution을 지정하지 않은 경우
        System.out.println("해상도 : " + b1.resolution);

        System.out.println("---------------------");

        BlackBox b2 = new BlackBox();
        b2.setModelName("하양이");
        b2.setPrice(-5000);
        b2.setColor("화이트");

        System.out.println("가격 : " + b2.getPrice() + "원"); // 가격 : 100000원
        System.out.println("해상도 : " + b2.getResolution()); // 해상도 : 판매자에게 문의하세요.

        // 이런식으로 getter와 setter을 이용하면 값을 지정하거나 불러올 때 발생하는 오류나 실수를 방지할 수 있다.
    }
}

 

package nadocoding.Chap_07;

public class BlackBoxRefurbish {
    // _10
    public String modelName; // 모델명
    String resolution; // 해상도 // default 생략 상태
    private int price; // 가격
    protected String color; // 색상

    // 변수만 만든 상태에서 Code -> Generate -> Getter and Setter -> 대상 지정 하면 getter와 setter를 한꺼번에 자동으로 생성 가능

    public String getModelName() {
        return modelName;
    }

    public void setModelName(String modelName) {
        this.modelName = modelName;
    }

    public String getResolution() {
        if (resolution == null || resolution.isEmpty()) {
            return "판매자에게 문의하세요.";
        }
        return resolution;
    }

    public void setResolution(String resolution) {
        this.resolution = resolution;
    }

    public int getPrice() {
        return price;
    }

    public void setPrice(int price) {
        if (price < 100000) {
            this.price = 100000;
        } else {
            this.price = price;
        }
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }
}

접근 제어자(access modifier)

package nadocoding.Chap_07;

public class _10_AccessModifier {
    public static void main(String[] args) {
        // 캡슐화 (Encapsulation) : 연관있는 변수, 메서드, 클래스 등 만 모아넣는 것
        // 정보은닉 (Information hiding) : 정보를 숨기는 것, 객체내에 있는 변수나 메소드의 직접적인 접근을 막는 것

        // 접근 제어자
        // private : 해당 클래스 내에서만 접근 가능
        // public : 모든 클래스에서 접근 가능
        // default : (아무것도 적지 않았을 때) 같은 패키지 내에서만 접근 가능
        // protected : 같은 패키지 내에서 접근 가능, 다른 패키지일 경우 자식 클래스(상속에서 다룸)에서 접근 가능

        // ctrl + R 을 통해 원하는 글자를 다른 글자로 한꺼번에 변경 가능
        BlackBoxRefurbish b1 = new BlackBoxRefurbish();
        b1.modelName = "까망이";
        // b1.resolution = "FHD";
        b1.setPrice(200000); // pirce에 private을 추가해 접근이 불가능하므로 getter와 setter로만 접근해야함.
        b1.color = "블랙";

        b1.setPrice(-5000);
        System.out.println("가격 : " + b1.getPrice() + "원");

        System.out.println("해상도 : " + b1.resolution);

        System.out.println("---------------------");

        BlackBox b2 = new BlackBox();
        b2.setModelName("하양이");
        b2.setPrice(-5000);
        b2.setColor("화이트");

        System.out.println("가격 : " + b2.getPrice() + "원");
        System.out.println("해상도 : " + b2.getResolution());


    }
}

 

package nadocoding.Chap_08;

import nadocoding.Chap_07.BlackBoxRefurbish;

public class _00_AccessModifierTest {
    public static void main(String[] args) {
        BlackBoxRefurbish b1 = new BlackBoxRefurbish();
        b1.modelName = "까망이"; // public
        // b1.resolution = "FHD"; // default
        // b1.price = 200000; // private
        // b1.color = "블랙"; // protected
    }
}

 

생각보다 진도가 느리다. 슬슬 처음보는 내용들이 나오다 보니 강의를 멈추고 코드를 돌아보는 시간이 길어지다 보니 그런 것 같다.

늦어도 다음주 수요일까진 지금 듣는 강의를 마치고, 다다음주부터는 내일배움캠프 시작과 동시에 웹개발 프로젝트를 한다고 하니 다음주 목,금요일은 웹개발종합반 강의 4~5주차를 재수강하고 부족하다면 주말까지 공부시간을 늘려야 할 것이다.

'TIL > JAVA' 카테고리의 다른 글

23.05.23  (0) 2023.05.23
23.05.22  (0) 2023.05.22
23.05.03  (0) 2023.05.03
23.05.02  (0) 2023.05.02
23.05.01  (0) 2023.05.01