본문 바로가기

IT/Java

11_상속(inheritance) : 다형성(Polymorphism), 자동형변환(Promotion), 강제형변환(Casting), instanceof 연산자, 추상클래스(abstract class)

01. 다형성

- 같은 타입이지만 실행 결과가 다양한 객체를 이용할 수 있는 성질. 하나의 타입에 여러 객체를 대입하여 만든다.

 

02. 자동형변환(Promotion)과 강제형변환(Casting)

- 부모 타입에는 모든 자식 객체가 대입될 수 있다.

- 부모 타입으로 자동형변환된 자식객체는 강제형변환을 통해 다시 자식 타입으로 바꿀 수 있다.

- 인터페이스 타입에는 모든 구현 객체가 대입될 수 있다.

 

 

예제) Dog 클래스가 Animal 클래스를 상속함

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class Animal {
    //필드
    String kind;
    
    //생성자
    public Animal(String kind) {
        this.kind = kind;
    }
    
    //메소드
    public void eat() {
        System.out.println("the animal is eating");
    }
 
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class Dog extends Animal {
 
    public Dog(String kind) {
        super(kind);
    }
    
    public void eat() {
        System.out.println("the dog is eating");
    }
    
    public void sound() {
        System.out.println("waf waf");
    }
    
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
 

 

- 부모타입(Animal)으로 생성된 animal 객체에는 자식타입(Dog)으로 생성한 객체를 담을 수 있다. (자동형변환 #11)

- 그러나 자식타입으로 생성된 객체에는 부모타입 객체를 담을 수 없다. 정 담고싶다면 강제형변환을 한다.

- 단, 강제형변환은 promotion을 거친 객체에 한해서만 가능하다. 즉, 부모형으로 자동형변환되었던 자식객체를 다시 자식의 타입으로 되돌릴 때만 쓸 수 있다. (#18~#21)

- 내가 생성한 객체가 어떤 클래스의 인스턴스인지 확인하기 위해 instanceof 연산자를 사용할 수 있다. (#13~#14)

 

03. 추상클래스

 

- 객체를 생성할 수 있는 클래스를 실체 클래스라고 한다.

- 이러한 실체 클래스들의 공통적인 특성을 추출해서 선언한 클래스를 추상클래스라고 한다. abstact 키워드를 붙여서 선언한다. 추상클래스는 객체를 직접 생성할 수 없고 상속을 통해 해결한다.

- 추상클래스의 용도

   1) 실체 클래스들의 공통된 필드와 메소드 이름 통일

   2) 실체 클래스 작성시 시간 절약

 

** 추상메소드

 - 메소드의 선언부만 있고 실행 내용인 중괄호{ } 가 없다. 추상클래스에서만 선언할 수 있다.

 - 하위메소드에서 반드시 실행 내용을 채우도록 강요하고 싶은 메소드가 있다면 추상메소드로 선언한다(강제성)

 - 자식클래스에서 추상메소드를 오버라이딩 하지 않으면 컴파일 에러가 발생한다 (=추상메소드는 반드시 오버라이딩 되어야 한다)

 

예제 )

- Dog 클래스와 Cat 클래스는 Animal(추상클래스)를 상속한다

- Animal 클래스의 public void sound(); 메소드는 반드시 오버라이딩 되어야 한다 (추상메소드로 선언)

 

1
2
3
4
5
6
7
8
9
10
public abstract class Animal {
    public String kind;
    
    public void breathe() {
        System.out.println("숨을 쉽니다");
    }
    
    public abstract void sound();    //추상메소드로 선언
 
}
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
 

 

추상클래스의 sound(); 메소드가 Dog, Cat 클래스에 맞게 각각 재정의 되었다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package ex06_abstract;
 
public class Dog extends Animal{
    public Dog() {
        this.kind = "포유류";
    }
    
    @Override
    public void sound() {    //재정의
        System.out.println("멍멍");
    }
 
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
 
 
1
2
3
4
5
6
7
8
9
10
11
12
public class Cat extends Animal {
    public Cat() {
        this.kind = "포유류";
    }
    
    @Override
    public void sound() {
        System.out.println("야옹");
    }
 
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
 

 

- 추상클래스로는 직접 객체 생성이 불가능하지만, 하위클래스로 생성한 객체를 추상클래스의 타입으로 바꿀 수는 있다. (#9 ~ #12)

 

- animalSound 메소드는 모든 Animal 타입을 받을 수 있다.

- 매개변수로 Dog 타입을 주면 Dog클래스의 sound() 메소드가, Cat 타입을 주면 Cat클래스의 sound() 메소드가 실행 된다.

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
public class AnimalExample {
    public static void main(String[] args) {
        Dog dog = new Dog();
        Cat cat = new Cat();
        dog.sound();
        cat.sound();
        System.out.println("========================");
        
        //자동형변환
        Animal animal = new Dog();
        animal.sound();
        System.out.println("========================");
        
        //다형성
        animalSound(new Dog());
        animalSound(new Cat());
        
    }
    
    public static void animalSound(Animal animal) {    //모든 동물 객체를 받을 수 있음
        animal.sound();
    }
 
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter