JAVA (6) : 인터페이스

Chloé·2023년 4월 17일
0

💻 JAVA

목록 보기
6/7

상속


코드 리뷰

public class ElvesTest {
  public static void main(String[] args) {
    // 엘프 객체 생성 & 업캐스팅(부모 타입으로 해석)
    Elf a = new Elf("티란데", 100);
    HighElf b = new HighElf("알퓨리온", 160, 100);
    ElfLoad c = new ElfLoad("마이에브", 230, 140, 100);
  }
  
  class Elf {
    protected String name;
    protected int hp;
    
    public Elf(String name, int hp) {
      this.name = name;
      this.hp = hp;
    }
    ...
  }
  
  class HighElf extends Elf {
    protected int mp;
    
    public HighElf(String name, int hp, int mp) {
      super(name, hp);	// 부모 클래스 생성자 호출;
      this.mp = mp;
    }
    ...
  }
  
  class ElfLoad extends HighElf {
    protected int sh;
    
    public ElfLoad(String name, int hp, int mp, int sh) {
      super(name, hp, mp, sh);	// 부모 클래스 생성자 호출;
      this.sh = sh;
    }
    ...
  }
}

업캐스팅 (부모 타입으로 해석)

public class ElvesTest {
  public static void main(String[] args) {
    // 엘프 객체 생성 & 업캐스팅
    Elf a = new Elf("티란데", 100);
    Elf b = new HighElf("알퓨리온", 160, 100);
    Elf c = new ElfLoad("마이에브", 230, 140, 100);
  
    // ArrayList로 묶기!
    ArrayList<Elf> list = new ArrayList<Elf>();
    list.add(a);
    list.add(b);
    list.add(c);
    
    // 반복을 통한 출력!
    for (int i; i < list.size(); i++) {
      System.out.println(list.get(i).toString());
    }
  }
  
  class Elf {
    ...
    public String toString() {
      return String.format("[엘프] Name: %s, HP: %d", name, hp);
    }
  }
  
  class HighElf extends Elf {
    ...
    // 메소드 오버라이딩
    public String toString() {
      return String.format("[하이엘프] Name: %s, HP: %d, MP: %d", name, hp, mp);
    }
  }
  
  class Elf {
    ...
    // 메소드 오버라이딩
    public String toString() {
      return String.format("[하이엘프] Name: %s, HP: %d, MP: %d, SH: %d", name, hp, mp, sh);
    }
  }
}

개념 확인하기!

  • class A extends B: B를 확장하여 A클래스를 생성
  • 메소드 오버라이딩: 부모 메소드를 자식에서 재정의
  • new ArrayList(): Elf를 담기위한 객체 생성
  • protected: 상속 관계 접근 허용
profile
안녕하세용

0개의 댓글