오류노트

[코딩 오류 노트] 상속, 오버라이딩

망고고래 2023. 10. 20. 17:40

1. 오버라이딩한 함수 static 설정

오류 메시지

This static method cannot hide the instance method from Student1

The method say() of type Leader must override or implement a supertype method

Cannot use super in a static context

 

코드

@Override

static void say() {

System.out.println("선생님께 인사");

super.say();

 

해결

상속받은 메서드를 오버라이딩하면서 스태틱 메서드로 만들 수는 없다.

 

 

 

2. main 메서드에서 super 호출

오류 메시지

Exception in thread "main" java.lang.Error: Unresolved compilation problem:

Cannot use super in a static context

 

코드

public static void main(String[] args) {

super.say();

 

해결

static 영역에서는 super를 사용해 인스턴스 멤버에 접근할 수 없다.

메인이 속해있는 클래스라 해도 인스턴스 생성 전까지는 존재하지 않는다.

 

 

 

3. 오버라이딩하지 않은 메서드 위에 '@Override' 기입

오류 메시지

The method say() of type lead must override or implement a supertype method

 

코드

@Override

void lead()

{

 

}

 

해결

오버라이딩하지 않은 메서드 위에 임의로 기입하지 않도록 한다.

 

 

 

4. static 메서드를 오버라이딩

오류 메시지

Exception in thread "main" java.lang.Error: Unresolved compilation problems:

This instance method cannot override the static method from Student1

The method say() of type Leader must override or implement a supertype method

 

코드

class Student1

{

    static void say()

    {

        System.out.println("선생님 안녕하세요!");

    }

}

 

class Leader extends Student1

{

 

    @Override

    void say() {

        System.out.println("선생님께 인사");

        super.say();

    }

 

}

static 메서드는 오버라이딩할 수 없다.

 

 

 

5. static 메서드를 오버라이딩하고 static으로 지정

오류 메시지

The method say() of type Leader must override or implement a supertype method

Cannot use super in a static context

 

코드

class Student1

{

    static void say()

    {

        System.out.println("선생님 안녕하세요!");

    }

}

 

class Leader extends Student1

{

    @Override

    static void say() {

        System.out.println("선생님께 인사");

        super.say();

    }

 

}