본문 바로가기
자바(Java)/자바기초

[자바기초.012] 상속(Inheritance)

by 긱펀 2024. 3. 13.
반응형

[자바기초.012] 상속(Inheritance)

 

[1] 상속(Inheritance) 란?

  • Object-Oriented programming에서 가장 큰 특징 중 하나가 상속(Inheritance)이다
  • 일상 생활속에서 "상속"은 부모로부터 재산을 "상속 받는다"라고 할때 사용되는데, 자바에서도 그 의미가 비슷하다.
  • 자바에서 모든 클래스(Class)는 attributes (instance variables / field)behaviors (methods)를 다른 클래스로부터 상속받을 수 있다.
  • 상속을 준 클래스는 "parent class or superclass"라고 하고,  상속을 받은 클래스는 "child class or subclass" 라고 부른다.

  • 클래스 상속을 받기 위해서 Java keyword "extends" 를 사용한다.(아래 사용예시 참고)
1
2
public class Car extends Vehicle
public class Motorcycle extends Vehicle
cs

 

[주의]
-자바는 오직 1개의 부모클래스로부터 상속 받을 수 있고, 2개 이상의 부모 클래스를 둘 수 없다.
-extends를 적지 않으면, 자바에서는 기본적으로 Object 클래스를 상속받게 되어 있다.

 

 

[2] 상속을 사용하는 이유

  • 상속은 부모 클래스의 field와 method를 재사용할 수 있는 장점이 있습니다.
  • 만약, 여러개의 클래스중 일부 field와 method가 공통적으로 사용되고 있다면, 그 field와 method를 부모클래스로 빼내어  상속관계를 만들면 됩니다. 이를 일반화(generalization)이라고 합니다.
  • 예를 들어, Customer와 Employees 클래스가 name과 address라는 field를 공통적으로 사용한다면, 아래 그림과 같이 Person 클래스를 만들고 그 안에 name과 address field를 넣어두고 상속 관계를 만들면 됩니다.
  • 아래의 이미지에서, Customer클래스는 creditCardInfo라는 고유의 데이터를 가지고 있고, Employee클래스는 id라는 고유의 데이터를 가지고 있다. 따라서 상속은, 각 클래스가 서로 공통의 데이터를 공유하지만, 각자의 고유 데이터를 구분해서 사용할 때도 유용하다. 이런 특징을 특수화(specializqtion)이라고 한다.

 

 

 

[예제1] 아래의 코드를 보며 상속관계를 이해해보자.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Person
{
    private String name;
}
 
// How can we make the Student class inherit from class Person?
public class Student extends Person
{
    private int id;
 
    public static void main(String[] args)
    {
        Student s = new Student();
        System.out.println(s instanceof Student);    // true
        System.out.println(s instanceof Person);     // true
    }
}
cs

 

 

  • 위의 코드에서, Student 클래스가 Person 클래스를 상속받았습니다.
  • 상속을 표시할 때는 자식 클래스에 extends를 사용한다.
  • instance of  연산자는 객체(object)가 어떤 클래스인지, 어떤 클래스를 상속받았는지 확인하는데 사용하는 연산자 입니다.
1
2
3
4
5
6
7
8
 
    Parent parent = new Parent();
    Child child = new Child();
 
    System.out.println( parent instanceof Parent );  // true
    System.out.println( child instanceof Parent );   // true
    System.out.println( parent instanceof Child );   // false
    System.out.println( child instanceof Child );   // true
cs

 

 

[유제1] 아래의 코드에서  /*  (1)  */ 에 들어갈 코드를 완성하세요.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import java.util.*;
 
class Test {
  String name = "Test";
}
 
 
public class Main /*  (1) */ {
  public static void main(String[] args) {
    Main m = new Main();
    Test t = new Test();
    
    System.out.println(m instanceof Test);
    System.out.println(m instanceof Main);
    System.out.println(t instanceof Test);
    System.out.println(t instanceof Main);
  }
}
 
cs

 


[유제 정답은 아래 "더보기" 클릭]

더보기

[유제1 정답]

extends Test

 

 

 

 

 


 

728x90
반응형

댓글