Java 코드연습/상속

[뉴렉처] Override(우선순위가 높은) 메소드

양상추상츄 2021. 10. 30. 22:40

NewlecExam에 total() 메소드가 있었으면

NewlecExam.total(); 이 실행 되었겠지만 없으면

차선책으로 Exam.total()이 실행되게됨

 

만약에 NewlecExam.total(); 을 정의한다면 오버라이드 메소드가 되고 우선 순위가 Exam.total()이 아닌

NewlecExam.total();가 우선순위가 된다. (오버라이드된 메소드가 우선순위가 더 높음)

 

 

Ctrl + Spacebar를 누르면 아래와 같이 나옴

import Exam_1.UI코드분리하기.Exam;

public class Program {

	public static void main(String[] args) {
		NewlecExam exam = new NewlecExam();
		
		exam.setMath(10);//지금은 일일히 점수입력해야해서 불편함
		exam.setKor(10);//자식 생성자에서 초기화하는 방법이 필요한 단계
		exam.setEng(10);
		exam.setCom(10);
		
		System.out.println(exam.total());
		
	}

}
import Exam_1.UI코드분리하기.Exam;

public class NewlecExam extends Exam {
	private int com;

	public int getCom() {
		return com;
	}

	public void setCom(int com) {
		this.com = com;
	}
	
	@Override
	public int total() {
		return super.total()+com;//부모의 total (국어, 영어, 수학의 합)에 com만 더 해주면됨
	}
	
	@Override
	public float avg() {
		
		return total()/4.0f; //여기서 total은 자식 total
	}
	
}

super를 앞에 붙이면 부모메소드 호출

자식클래스가 오버라이드한 메소드가 우선적으로 호출되지만

만약 부모의 메소드에 들어가는 매개변수 처럼 입력하면 부모클래스의 메소드가 호출됨