# 리뷰: 엘프의 연속 확장 메소드 리턴부분에서 this, super 없이도 수행되는 이유가 궁금합니다. #### CODE <a class='btn btn-default' href='/codes/90779'>Link</a> ``` public class ElvesTest { public static void main(String[] args) { // 객체 생성 Elf elf = new Elf("티란데", 100); HighElf high = new HighElf("말퓨리온", 160, 100); ElfLord lord = new ElfLord("마이에브", 230, 140, 100); // 객체 배열 생성 Elf[] elves = { elf, high, lord}; for(int i =0; i< elves.length; i++){ System.out.println(elves[i].toString()); } // 모든 객체 정보 출력 } } class Elf { /* 1. 상속을 위한 접근 제한자를 사용하세요. */ protected String name; protected int hp; //생성자 public Elf(String name, int hp) { this.name = name; this.hp = hp; } public String toString() { return String.format("[엘프] Name: %s, HP: %d", name, hp); } } class HighElf extends Elf { protected int mp; public HighElf(String name, int hp, int mp) { super(name, hp); this.mp = mp; } //메소드 오버라이딩 public String toString() { return String.format("[하이엘프] Name: %s, HP: %d, MP: %d", name, hp, mp); } } class ElfLord extends HighElf { protected int shield; public ElfLord(String name, int hp, int mp, int shield) { super(name, hp, mp); this.shield = shield; } /* 3. toString() 메소드를 오버라이딩(재정의) 하세요. */ public String toString() { return String.format("[엘프로드] Name: %s, HP: %d, MP: %d, SH: %d", name, hp, mp, shield); } } ``` #### INPUT ``` ``` #### OUPUT ``` [엘프] Name: 티란데, HP: 100 [하이엘프] Name: 말퓨리온, HP: 160, MP: 100 [엘프로드] Name: 마이에브, HP: 230, MP: 140, SH: 100 ```
상속객체의 인스턴스 변수는 기본적으로 this를 가정합니다. 따라서, 모든 변수에 this가 자동 기입됩니다 그러므로 this영역에서 name, hp, mp, shield를 모두 찾는데 없는 경우 super로 영역으로 올라가며 자동적으로 대상을 찾습니다 이러한 이유로 this와 super가 생략 가능합니다
답변 감사합니다!!
많은 공유 부탁스 아님 500원