[Java] 클래스, 객체, 인스턴스의 차이 - Heee's Development Blog
class A {}
선언 후 class B extends A {}
로 클래스 B를 정의하면 기존 멤버 변수 및 상수를 동일하게 사용할 수 있다.class Animal {
toString() {
return "";
}
}
class Lion extends Animal {
toString() {
// toString 오버라이딩
return "사자";
}
}
class Husky extends Animal {
toString() {
// toString 오버라이딩
return "허스키";
}
}
class Master {
feed(animal) {
console.log(animal.toString(), "에게 먹이를 줬다!");
}
}
lion = new Lion();
husky = new Husky();
master = new Master();
master.feed(lion); // 사자 에게 먹이를 줬다!
master.feed(husky); // 허스키 에게 먹이를 줬다!
.prototype.[key] = …
를 입력하여 설정할 수 있으며, 메서드
나 속성
처럼 동작한다.function Animal(type, name, sound) {
this.type = type;
this.name = name;
this.sound = sound;
}
Animal.prototype.say = function () {
console.log(this.sound);
};
Animal.prototype.sharedValue = 1;
function Dog(name, sound) {
Animal.call(this, "개", name, sound);
}
Dog.prototype = Animal.prototype;
function Cat(name, sound) {
Animal.call(this, "고양이", name, sound);
}
Cat.prototype = Animal.prototype;
const dog = new Dog("멍멍이", "멍멍");
const cat = new Cat("야옹이", "야옹");
dog.say(); // 멍멍
cat.say(); // 야옹
console.log(dog.sharedValue); // 1
console.log(cat.sharedValue); // 1
.prototype
을 할당해주면 상속
받는 효과를 줄 수 있다.프로토타입
을 이용하여 객체 상속을 구현해서 사용했다.class 문법
이 추가되었기 때문에, 같은 효과인 class 문법을 더 권장한다.this
키워드는 현재 클래스의 참조를 가리키며, super
키워드는 부모 클래스의 참조를 가리킨다.super()
는 함수 형태 호출해야 하며 부모 클래스의 생성자 함수를 호출하여 넘겨주면 현재 클래스의 속성처럼 사용할 수 있다. super() 호출 위에 this
키워드가 사용되어서는 안된다.class Polygon {
constructor(height, width) {
this.name = "Polygon";
this.height = height;
this.width = width;
}
}
class Square extends Polygon {
constructor(length) {
// this.height; // 참조오류가 발생. super가 먼저 호출되어야 함.
// 여기서, 부모클래스의 생성자함수를 호출하여 높이값을 넘겨줌.
// Polygon의 길이와 높이를 넘겨줍니다.
super(length, length);
// 참고: 파생 클래스에서 super() 함수가 먼저 호출되어야
// 'this' 키워드를 사용할 수 있습니다. 그렇지 않을 경우 참조오류가 발생합니다.
this.name = "Square";
}
get area() {
return this.height * this.width;
}
set area(value) {
this.area = value;
}
}
두문자 | 약어 | 개념 | 설명 |
---|---|---|---|
S | SRP | 단일 책임 원칙 (Single responsibility principle) | - 한 클래스는 하나의 책임만 가져야 한다. |
O | OCP | 개방-폐쇄 원칙 (Open/closed principle) | - “소프트웨어 요소는 확장에는 열려 있으나 변경에는 닫혀 있어야 한다.” |
L | LSP | 리스코프 교환 원칙 (Liskov substitution principle) | - “프로그램의 객체는 프로그램의 정확성을 깨뜨리지 않으면서 하위 타입의 인스턴스로 바꿀 수 있어야 한다.” |
I | ISP | 인터페이스 분리 원칙 (Interface segregation principle) | - “특정 클라이언트를 위한 인터페이스 여러 개가 범용 인터페이스 하나보다 낫다.” |
D | DIP | 의존관계 역전 원칙 (Dependency inversion principle) | - 프로그래머는 “추상화에 의존해야지, 구체화에 의존하면 안된다.” - 의존성 주입은 이 원칙을 따르는 방법 중 하나다. |
캡슐화
해야 한다는 의미이다.대체
할 수 있다.부모 클래스
가 들어갈 자리에 자식 클래스
를 넣어도 잘 작동해야 한다는 의미.확장
만을 수행하도록 해야 한다.