22.5.09 [HackerRank]Java Method Overriding 2 (Super Keyword)

서태욱·2022년 5월 9일
0

Algorithm

목록 보기
37/45
post-thumbnail

✅ 문제 분석

서브클래스의 메서드가 슈퍼클래스의 메서드를 재정의하는 경우에 super 키워드를 사용하여 재정의된 메서드를 호출할 수 있다.

func() 함수를 호출하기 위해 super.func() 를 작성 하면 슈퍼클래스에 정의된 메서드를 호출한다.

following text를 출력하도록 주어진 코드를 수정하는 문제.

🌱 배경지식

super와 super()

super키워드는 수퍼 클래스로부터 상속받은 필드나, 메소드를 서브 클래스에서 참조할 때 사용하는 참조 변수다.

인스턴스 변수 이름이 지역변수와 같을 경우 인스턴스 변수 앞에 this.라는 키워드로 구분해주었듯이,
수퍼 클래스와 서브 클래스의 멤버 이름이 같을 경우 super 키워드로 구별해줄 수 있다.

메소드를 오버라이딩 할 때 수퍼 클래스의 메소드를 완전히 대치하기보다 내용을 추가하는 경우가 많다. 이럴 때 super 키워드를 사용해 super 클래스의 메소드를 호출해 준 뒤에 자신이 필요한 부분을 추가해 주는 것이 좋다.

/* Parent 클래스 */
class Parent {
    public void print() {
        System.out.println("부모 클래스의 print() 메소드");
    }
}

/* Child 클래스 */
public class Child extends Parent {
    public void print() {
        super.print();
        System.out.println("자식 클래스의 print() 메소드");
    }

    public static void main(String[] args) {
        Child obj = new Child();
        obj.print();
    }
}

//[실행결과]
부모 클래스의 print() 메소드
자식 클래스의 print() 메소드

super()는 자바 컴파일러가 수퍼 클래스의 생성자를 명시적으로 호출하지 않는 모든 서브 클래스의 생성자 첫 줄에 자동으로 추가하여 수퍼 클래스 멤버를 초기화하는 명령문이다.

class Parent {

    int a;

    Parent() { a = 10; }

    Parent(int n) { a = n; }

}

 

class Child extends Parent {

    int b;

    Child() {//super(40);

        b = 20;

    }

    void display() {

        System.out.println(a);

        System.out.println(b);

    }

}

 

public class Inheritance04 {

    public static void main(String[] args) {

        Child ch = new Child();

        ch.display();

    }

}
//실행결과
10

20

예제를 실행하면, 자바 컴파일러는 주석 처리된 ①번 라인에 자동으로 super(); 구문을 삽입한다. 변수 a는 10으로 초기화된다.

하지만 ①번 라인 주석 처리을 해제하면, 수퍼 클래스인 Parent 클래스는 두 번째 생성자에 의해 초기화된다.

따라서 변수 a는 40으로 초기화된다.

✏️ 해설

import java.util.*;
import java.io.*;


class BiCycle{
    String define_me(){
        return "a vehicle with pedals.";
    }
}

class MotorCycle extends BiCycle{
    String define_me(){
        return "a cycle with an engine.";
    }

    MotorCycle(){
        System.out.println("Hello I am a motorcycle, I am "+ define_me());

        String temp=super.define_me(); //Fix this line

        System.out.println("My ancestor is a cycle who is "+ temp );
    }

}
class MethodOverriding2{
    public static void main(String []args){
        MotorCycle M=new MotorCycle();
    }
}

👉 참고

profile
re:START

0개의 댓글