Dev.GA

[JAVA] 상속(Inheritance)이란? 본문

Dev.Back-End/JAVA

[JAVA] 상속(Inheritance)이란?

Dev.GA 2018. 2. 28. 00:37


[JAVA] 상속(Inheritance)이란?



1. 상속(Inheritance)이란?


상속이란 일반적으로 우리의 실생활에서도 쓰는 용어이다.

부모가 자식에게 재산을 물려주는 행위를 가르켜 상속이라 말한다.

Java에서도 상속은 비슷한 의미로 사용되고 있다.


Java에서 상속은 부모 클래스의 변수/메소드를 자식 클래스가 물려받아 그대로 사용 가능하게 해준다.

여기서 부모클래스를 superclass, 자식클래스를 subclass라 부른다.


자식클래스에서 A라는 기능을 처리하는데 부모클래스에서 이미 똑같은 A라는 기능을 처리하고 있다면

자식클래스는 이를 상속받아 그대로 사용할 수 있으며, 코드의 중복을 막아준다.


상속은 extends라는 키워드를 사용하며 상속의 형태는 다음과 같다.


자식클래스 extends 부모클래스


다음 코드를 통해 간단히 확인해보자.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
public class Inheritance {
 
    public class ParentClass{
        String parent = "I am parent";
        
        public void Parent(){
            System.out.println("I am Parent Method() in ParentClass");
        }
    }
    
    public class ChildClass extends ParentClass{
        String child = "I am child";
        
        public void Child(){
            Parent();
            System.out.println(parent);
            System.out.println("I am Child Method() in ChildClass");
            System.out.println(child);
        }
    }
    
    public static void main(String[] args) {
        Inheritance inheritance = new Inheritance();
        ChildClass cc = inheritance.new ChildClass();
        cc.Child();
    }
 
}
cs


위의 코드를 실행해보면,


I am Parent Method() in ParentClass

I am parent

I am Child Method() in ChildClass

I am child


실행순서)


1. Parent() 메소드


위와 같이 최초 실행된 14번째 라인) ChildClass(자식클래스)의 Child() 메소드가 부모클래스(ParentClass)로부터 상속받은 Parent()메소드를 호출한다. Parent클래스는 "I am Parent Method() in ParentClass"라는 메세지를 출력한다.


2. parent 변수


16번째 라인) 자식클래스(ChildClass)는 부모클래스(ParentClass)로부터 상속받은 String타입의 parent변수를 출력한다.


3. ChildClass 출력 실행


17,18번째 라인) 에서 ChildClass 본인의 메세지들을 순서대로 출력해준다.


이렇게 상속을 통해 자식클래스는 부모클래스의 속성을 그대로 물려받아 사용할 수 있다.


하지만 Java에서 상속은 다중상속을 지원하지 않는데, 이런 경우 어떻게 해야하나?


Implements라는 것이 존재한다.



2. Implements(인터페이스 구현)


Implements라는 녀석으로 다중상속을 가능하게 해준다.


implements를 통해 부모클래스에서 선언한 변수/메소드를 자식클래스에서 재정의(오버라이딩)를 통해 인터페이스를 구현하여 상속받을 수 있다. 여기서 잠시 인터페이스와 클래스의 차이점을 간단히 보면, 인터페이스는 메소드를 구현하지않고 정의만 내리며 이 인터페이스를 상속받은 클래스에서 해당 인터페이스에서 정의된 메소드를 구현하는 것이라 생각하면 된다.


따라서, extends는 클래스를 확장하는 것이며 implements는 인터페이스를 구현하는 것이다.


public class ChildClass implements FatherClass, MotherClass{

}


위와 같은 형태로 implements는 다중상속이 가능하게 해준다.


오늘은 Java에 상속에 대해서 알아보았다.



Comments