@implementation Shape 에 구현해 놓은 메소드들을 보자. @implementation Shape - (void) setFillColor : (ShapeColor) c { fillColor = c; } - (void) setBounds : (ShapeRect) b { bounds = b; } - (void) draw { // draw 는 구현하지 않는다. } @end Shape 에서 draw 를 구현하지는 않지만 하위 클래스가 상속받아 구현하도록 항상 정의한다. 하위 클래스에서 -(void) draw 를 구현하면 된다.
@interface Circle : NSObject @interface 지시자 다음에는 클래스 이름이 따라온다. 콜론(:) 뒤에 오는 식별자가 상속받으려는 상위 클래스의 이름이다. Objective-C 는 다중 상속을 지원하지 않는다. @interface Circle : Shape @end // Circle @interface Rectangle : Shape @end // Rectangle * Circle과 Rectangle의 인터페이스를 Shape에서 상속
Circle fillColor bounds setFillColor: setBounds: draw Rectangle fillColor bounds setFillColor: setBounds: draw 이와 같이 중복되는 부분이 많으면 비효율 적이다. 중복되는 코드를 한곳에 합쳐서 정리 하는 방법 - 상속. Shape 클래스를 상속받아 Circle 과 Rectangle 를 정의 하면 이와 같다. Circle 클래스를 수퍼클래스( 부모클래스 )라 부른다. Circle 과 Rectange 클래스를 서브클래스 ( 자식클래스 ). Circle 과 Rectangle 은 Shape 로 부터 상속을 받았기 때문에 Shape의 인스턴스 변수 fillColor 와 bounds 를 받는다. 메소드 또한 상속.
* 메소드 선언 (method declarations) : 내가 지원하는 기능이라고 선언 - (void) draw; - (void) setFillColor: (ShapeColor) fillColor; - (void) setBounds: (ShapeRect) bounds; ----------------------------------------------- - (반환타입) 메소드 이름: (반환타입) 인수; - 기호는 메소드를 선언한다는 의미.
@interface Circle : NSObject + @interface Circle : 컴파일러에게 "Circle이라는 이름을 갖는 새 클래스를 위한 인터페이스가 있다"고 알려준다. + NSObject : 컴파일러에게 "Circle클래스가 NSObject 클래스를 기반으로 한다"는 것을 알려준다. 모든 Circle은 NSObject이기도 하며 또한 NSObject 클래스가 정의하고 있는 모든 것들을 상속받는다는 것을 알려준다.