본문으로 바로가기

클래스 상속 소개

클래스 상속을 사용하면 기존 코드를 변경하지 않고도 기능을 추가하거나 수정할 수 있습니다.

이 글에서는 클래스 상속 개념에 대해 간략히 알아봅니다.



클래스 상속이란?

객체지향 프로그래밍에서 상속의 개념은 현실에서 사용되는 상속이란 단어의 뜻과 유사합니다.

예를 들어, 자식이 부모로부터 유산을 상속받았다면 자식은 상속받은 재산을 사용할 수 있게 됩니다.

부모의 재산이 집, 땅, 현금 1억이 있다면 그 자식은 이를 물려 받을 수 있으며 자식은 부모로부터 상속받은 재산과 직접 만든 재산(자동차, 주식등..)을 가지고 있을 수 있습니다.

이러한 사전적인 상속의 개념은 프로그래밍에서도 상속이라고도 부르고 확장이라고도 부릅니다.

프로그래밍적으로 적용해 보면 특정 클래스(부모 클래스)의 속성과 메서드를 하위(자식) 클래스가 물려받는 것을 의미합니다.

상속을 받는 자식 클래스에서는 부모의 소스코드를 복사할 필요없이 부모 클래스의 기능과 속성을 모두 사용할 수 있을 뿐 아니라 필요한 기능을 추가해 확장할 수도 있습니다.


지금까지의 설명을 자바스크립트 코드로 표현하면 다음과 같습니다.

JavaScript
// MyParent 클래스
function MyParent() {
	this.property1 = 5;
}
MyParent.prototype.method1 = function () {
	console.log(this.property1);
};

// MyChild 클래스
function MyChild() {
	// MyChild 에는 method1() 이 존재하지 않는다.
}
// MyParent 클래스를 상속받는 문법
MyChild.prototype = new MyParent();

// 인스턴스 생성 및 호출
var child1 = new MyChild();

// 부모의 기능에 있는 method1() 메소드를 호출하도록 한다.
child1.method1();
// MyChild 에는 method1()이 없지만 MyParent를 상속받았기 때문에 코드 복사없이 재사용할 수 있다.


MyChild에는 method1()이라는 메서드를 만들지 않았지만 MyChild는 MyParent를 상속받았기 때문에 Myparent의 기능인 method1()를 사용할 수 있는 것입니다.

바로 이러한 기능이 상속(확장)입니다.




클래스 상속 기능

상속은 다음과 같이 세 가지 기능을 가지고 있습니다.

  • 코드 재사용성
  • 중복 코드의 제거
  • 확장


코드의 재사용성

JavaScript
// 부모 클래스
function Parent() {
	this.prop = 'value1';
}
Parent.prototype.method01 = function () {
	console.log('Parent.method01() ' + this.prop);
};

// 자식 클래스
function Child() {

}

// 상속하기
Child.prototype = new Parent();

// 인스턴스 생성
var child01 = new Child();

// 부모의 프로퍼티와 메서드를 호출
console.log('child01.prop = ' + child01.prop);
child01.method01();


위의 코드에서 확인할 수 있는 것처럼 상속을 사용하면 코드 복사없이 Child 클래스에서 Parent 클래스 요소인 prop과 method01()을 사용할 수 있는 것을 확인할 수 있습니다.

바로 이러한 경우를 코드의 재사용이라고 합니다.



중복 코드의 제거

클래스 상속은 중복 코드의 제거 기능을 가지고 있습니다.

다음의 예제를 통해 좀더 알아봅니다. 먼저 다음과 같은 코드가 있습니다.

JavaScript
// 첫 번째 : MyClassA
function MyClassA() {
	this.prop1 = 10;
}
MyClassA.prototype.method1 = function () {
	console.log('this.prop1 = ' + this.prop1);
};
MyClassA.prototype.mothod2 = function () {
	console.log('이 기능은 MyClassA 에 있는 기능입니다.');
};

// 두 번째 : MyClassB
function MyClassB() {
	this.prop1 = 10;
}
MyClassB.prototype.method1 = function () {
	console.log('this.prop1 = ' + this.prop1);
};
MyClassB.prototype.mothod2 = function () {
	console.log('이 기능은 MyClassB 에 있는 기능입니다.');
};

// 인스턴스 생성
var classA = new MyClassA();
// 프로퍼티와 메서드 접근(호출)
console.log('classA.prop1 = ' + classA.prop1); // classA.prop1 = 10
classA.method1(); // this.prop1 = 10
classA.mothod2(); // 이 기능은 MyClassA 에 있는 기능입니다.

var classB = new MyClassB();
// 프로퍼티와 메서드 접근(호출)
console.log('classB.prop1 = ' + classB.prop1); // classB.prop1 = 10
classB.method1(); // this.prop1 = 10
classB.mothod2(); // 이 기능은 MyClassB 에 있는 기능입니다.


위의 코드를 살펴보면 두개의 클래스에 중복 코드가 발생하고 있는 것을 확인할 수 있습니다.

위와 같은 중복 코드는 클래스 상속을 활용하면 중복 코드가 없는 좀 더 간결하고 깔끔한 코드를 작성할 수 있습니다.

상속을 활용해 중복 코드를 제거하는 방법은 간단합니다.


중복 코드를 담을 부모 클래스를 생성한다.

먼저 다음과 같이 신규 클래스(Myparent)를 만든 후 MyClassA와 MyClassB 클래스의 중복 코드를 신규 클래스에 담아주도록 합니다.

JavaScript
// 중복 코드를 담을 클래스
function MyParent() {
	this.prop1 = 10;
}
MyParent.prototype.method1 = function () {
	console.log('this.prop1 = ' + this.prop1 );
};


중복 코드의 제거와 상속관계 만들기

중복 코드를 MyParent 클래스에 담았다면 MyClassA와 MyClassB 클래스에서 사용되던 중복 코드를 제거해 주도록 합니다.

그리고 다음의 코드와 같이 상속으로 연결해 주도록 합니다.

JavaScript
// 중복 코드를 담을 클래스
function MyParent() {
	this.prop1 = 10;
}
MyParent.prototype.method1 = function () {
	console.log('this.prop1 = ' + this.prop1 );
};

// 첫 번째 : MyClassA
function MyClassA() {

}
// 상속
MyClassA.prototype = new MyParent();

MyClassA.prototype.mothod2 = function () {
	console.log('이 기능은 MyClassA 에 있는 기능입니다.');
};

// 두 번째 : MyClassB
function MyClassB() {

}
// 상속
MyClassB.prototype = new MyParent();

MyClassB.prototype.mothod2 = function () {
	console.log('이 기능은 MyClassB 에 있는 기능입니다.');
};

// 인스턴스 생성
var classA = new MyClassA();
// 프로퍼티와 메서드 접근(호출)
console.log('classA.prop1 = ' + classA.prop1); // classA.prop1 = 10
classA.method1(); // this.prop1 = 10
classA.mothod2(); // 이 기능은 MyClassA 에 있는 기능입니다.

var classB = new MyClassB();
// 프로퍼티와 메서드 접근(호출)
console.log('classB.prop1 = ' + classB.prop1); // classB.prop1 = 10
classB.method1(); // this.prop1 = 10
classB.mothod2(); // 이 기능은 MyClassB 에 있는 기능입니다.


중복 코드는 부모 클래스인 MyParent에 모두 담겨 있습니다. 

그리고 자식 클래스에서는 부모 클래스의 기능을 사용할 수 있게 됩니다.

이렇게 클래스 상속을 활용하면 중복 코드를 없앨 수 있을 뿐 아니라 코드를 재사용할 수 있습니다.




Jaehee's WebClub


'JavaScript > JS 객체지향 프로그래밍' 카테고리의 다른 글

prototype, constructor, 인스턴스  (1) 2016.09.29
멤버 접근 제어 구조  (0) 2016.09.29
객체 확장  (0) 2016.09.29
자바스크립트 상속 사용 예제  (0) 2016.09.29
Function 상속과 call,apply  (0) 2016.09.29