Skip to content

클래스 상속

상속은 클래스의 기능을 확장하고자 할때 현재의 클래스의 기능을 모두 가지고 자신만의 기능이 추가된 새로운 클래스를 정의 하는 방법이다. 따라서 상속을 하게 되면 클래스가 상, 하의 계층구조를 가지게 된다.

코틀린에서 모든 클래스는 공통의 상위클래스(superclass)로 Any 클래스를 가진다. 클래스에 상위 클래스를 선언하지 않아도 기본적으로 Any가 상위 클래스가 된다.

마치 JAVA에서 Object가 클래스의 기본 상위 클래스가 되는 것괴 비슷하다. 하지만 클래스 내용이 같지는 않다.

Any와 Object 비교

Kotlin의 Any보다 Java의 Object가 가지는 메서드의 수가 더 많다.

public open class Any {
public open operator fun equals(other: Any?): Boolean
public open fun hashCode(): Int
public open fun toString(): String
}
public class Object {
private static native void registerNatives();
static {
registerNatives();
}
public final native Class<?> getClass();
public native int hashCode();
public boolean equals(Object obj) {
return (this == obj);
}
protected native Object clone() throws CloneNotSupportedException;
public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
public final native void notify();
public final native void notifyAll();
public final native void wait(long timeout) throws InterruptedException;
public final void wait(long timeout, int nanos) throws InterruptedException {
if (timeout < 0) {
throw new IllegalArgumentException("timeout value is negative");
}
if (nanos < 0 || nanos > 999999) {
throw new IllegalArgumentException(
"nanosecond timeout value out of range");
}
if (nanos >= 500000 || (nanos != 0 && timeout == 0)) {
timeout++;
}
wait(timeout);
}
public final void wait() throws InterruptedException {
wait(0);
}
protected void finalize() throws Throwable { }
}

상속

특정 클래스를 상속받기 위해선 아래와 같이 코드를 작성해주면 된다.

open class Base(p: Int)
class Derived(p: Int) : Base(p)

파생 클래스가 기본 생성자를 가진다면, 베이스 클래스(base class)는 기본 생성자의 인자를 사용해서 바로 초기화 될 수 있어야 한다. 따라서, 클래스를 상속받을때 부모 클래스의 주 생성자를 어떻게 호출할지를 같이 적어줘야한다.