객체지향 프로그래밍

돌리의 하루·2023년 6월 6일
0

class : 작업지시서 : 이것 보고 만들어라~

class 안에 값을 넣어주는 constructor() //생성자

class안에 있는 name이야! => this.name

제품별로 class를 만든다.

제품별 class 중에서 겹치는 항목 ex) price항목이 겹침

그러면 겹치는 부분을

class Product {
	name = ""
	price = 0
}

이런 식으로 추상화 작업을 통해서 코드를 간단화 할 수 있음

product에 'type'이 추가된 class를 만들고 싶다?

class AC extends Product {
	type = "";
}

위와 같은 방식으로 만들면 간편함.

또한, 위와같은 extends방식으로 만들어진 class는 super를 쓰게 되는데,

class AC extends Product {
	type = "";
    	constructor(name, price, type) {
        	super(name,price) //product ((부모))의 속성
            this.type = type;
        }
}

와 같이 오게된다.

그렇다면 부모입장인 product에 코드를 추가해보자.

class Product {
	name = "";
    price = 0;
    	constructor(name, price) {
        	this.name = name;
            this.price = price;
        }
        getPrice() {
        	return this.price + '원'
        }
        setPrice(price){
        	if(price < 0) {
            	throw new Error ('마이너스 값은 존재하지않음')
            }
            this.price = price; //조건이 아닐경우 price 보여줌
        }
}

produce에 위와 같이 함수도 들어갈 수 있다. 변수들과 변수에 관련된 함수들을 같은 클래스에 넣을 수 있다.
캡슐화라고도 한다.

profile
진화중인 돌리입니다 :>

0개의 댓글