Java

[Java] 객체(클래스)

dalooong 2023. 7. 7. 11:34

클래스 Object Oriented Programmin = OOP

클래스란 ?

객체지향 프로그래으로 유지보수가 용이하며 높은 재사용성을 가진다.

  1. 클래스
public class _01_Class {
    //클래스
    public static void main(String[] args) {
        // 객체지향프로그래밍 (OOP:Object-Oriented-Programming)
        // 유지보수 용이
        // 높은 재사용성
        // 차량용 블랙박스
        // 모델명, 해상도, 가격, 색상

        //우리가 만든 첫번째 상품

        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 bbox2 = new BlackBox();

    }
}

2. 인스턴스 변수

public class _02_IntanseVariables {
    public static void main(String[] args) {
        //인스턴스 변수
        BlackBox b1 = new BlackBox(); //b1객체생성됨
        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 = 30000;
        b2.color = "화이트";

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

    }
}

BlackBox 설계 클래스

public class BlackBox {
    //설계도
    String modelName; //모델명
    String resolution; //해상도
    int price; // 가격
    String color; //색상

    //static~ 클래스 내에 클래스 변수
    static boolean canAutoReport = false; //자동신고기능

    void autoReport() {
     if(canAutoReport) {
         System.out.println("충돌이 감지되어 자동으로 신고합니다.");
     }else {
         System.out.println("자동 신고 기능이 지원되지 않습니다.");
     }
    }
    void insertMemortCard(int capacity){
        System.out.println("메모리 카드가 삽입되었습니다.");
        System.out.println("용량은 " + capacity + "GB 입니다.");
    }

    int getVideoFileConunt (int type){
        if (type == 1){ //일반영상
            return  9;
        } else if (type == 2) {
            return 1;
        }
        return 10;
    }
    //showDateTime : 날짜정보 표시여부
    //showSpeed : 속도정보 표시여부
    // min : 영상 기록 단위(분)

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

    void record(){
        record(true, true, 5);

    }
}

클래스 변수

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); //클래스명.으로 가야함

    }
}

메소드

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

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

        b1.insertMemortCard(256);

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

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

}

메소드 오버로딩

public class _05_MethodOverloding {
    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"));
    }
}

클래스 메소드

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

        String s = String.valueOf(3);

    }
}

This

public class _07_This {
    public static void main(String[] args) {
        BlackBox b1 = new BlackBox();
        b1.modelName ="까망이"; //까망이(최신형)
        b1.appendModelName("(최신형)");
        System.out.println(b1.modelName);
    }
}

생성자

public class _08_Constructor {
    public static void main(String[] args) {
        BlackBox b1 = new BlackBox();
        b1.modelName = "까망이";
        b1.resolution = "FHD";
        b1.price = 20000;
        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);
//        System.out.println(b2.resolution);
//        System.out.println(b2.price);
//        System.out.println(b2.color);
    }
}

Getter와 Setter

public class _09_GetterSetter {
    public static void main(String[] args) {
        BlackBox b1 = new BlackBox(); //새로운 객체 만듦
        b1.modelName = "까망이";
      //  b1.resolution = "FHD";
        b1.price = 20000;
        b1.color = "블랙";

        //할인 행사
        b1.price = -5000;
        System.out.println("가격 :" + b1.price + "원");

        // 고객 문의(해상도는?)
        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());

        b2.price = -5000;
    }
}

접근제어자

접근제어자란 접근을 제어하는 것

  • private : 해당 클래스 내에서만 접근이 가능
  • public : 모든 클래스에서 접근 가능
  • default : (아무것도 적지 않았을 때) 같은 패키지 내에서만 접근 가능
  • protected : 같은 패키지 내에서, 다른 패키지인 경우 자식 클래스에서 접근 가능
public class _10_AcessModifier {
    public static void main(String[] args) {
        //접근제어자 : 접근을 제어 하는 것
        //private : 해당 클래스 내에서만 접근 가능
        //public : 모든 클래스에서 접근 가능
        //default : (아무것도 적지 않았을 때) 같은 패키지 내에서만 접근 가능
        //protected : 같은 패키지 내에서, 다른 패키지인 경우 자식 클래스에서 접근 가능
        
        BlackBoxRefurbish b1 = new BlackBoxRefurbish(); //새로운 객체 만듦
        b1.modelName = "까망이";
        //  b1.resolution = "FHD";
        b1.setPrice(200000);
        b1.color = "블랙";

        //할인 행사
        b1.setPrice(-5000);
        System.out.println("가격 :" + b1.getPrice() + "원");

        // 고객 문의(해상도는?)
        System.out.println("해상도 : "+b1.resolution);

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

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

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

    }
}
📍
캡슐화 (Encapsulation): 서로 연관된 것들끼리 캡슐로 묶는 것
정보은닉(Information Hiding) : 객체에서 허용하는 메소드를 통해서만 접근 가능하게 하는 것