Notice
Recent Posts
Recent Comments
Link
«   2025/07   »
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 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

TMI개발일기

오버라이딩(overriding) 본문

백엔드/Java

오버라이딩(overriding)

JP59 2021. 3. 5. 14:40

이번에는 오버라이딩에 대해 알아보자.

 

오버라이딩은 상속받은 부모클래스의 메소드를 자식클래스에서 

 

사용 용도에 맞게 재정의하는것을 말한다.

 

코드로 알아보자.

 

 

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
29
30
31
32
33
34
35
36
37
38
 
 
class person{
    
    String name="chulsu";
    int age=18;
    int height=176;
    int weight=68;
    
    void say() { }
    void eat() {    }
    void breath() {    }
    
}
 
class student extends person {
    
    void study() {
        
    }
    
    void say() {
        
        System.out.println("hi!");
    }
}
 
public class ttt {
 
    public static void main(String[] args) {
        // TODO Auto-generated method stub
 
        student chulsu =new student();
        person who = new person();
        who.say();
        chulsu.say();
        
    }
cs

 

부모 클래스 person은 여러 메소드와 변수를 가지고 있는데

say()메소드는 아무런 값을 가지고 있지 않다.

student 클래스는 say()를 가져와서 메소드 사용 시

"hi!"라고 출력하게끔 재정의 했다. 메인문을 확인해보면 

student 클래스의 인스턴스인 'chulsu'와

person의 인스턴스인 'who'를 생성해서 

각각 메소드 say()를 실행해봤다.

 

결과값은 

 

sutdent클래스에서 재정의한(오버라이딩) chulsu.say()의 출력값이 "hi!"라고 나오게 된다.

 

 

그렇다면 오버라이딩한 메소드를 원래의 부모메소드로 호출하고 싶다면 어떻게 해야 할까?

이때는 super 연산자를 사용해서 부모 메소드를 사용하면 된다.

'백엔드 > Java' 카테고리의 다른 글

접근 제어자(access modifier)  (0) 2021.03.08
상속과 생성자 (extends and constructor)  (0) 2021.03.05
상속(extends)  (0) 2021.03.05
클래스 멤버와 인스턴스 멤버  (0) 2021.03.04
생성자 (constructor)  (0) 2021.03.03