Back end/Java 객체지향
super 예시
jinpark1992
2023. 11. 22. 17:11
super: 자식클래스에서 생성자를 만들때 부모 클래스의 메소드 값을 가져오기에 씀
public class SuperTest { public static void main(String[] args) { /* 1. Orc 객체를 만들고 정보를 출력하시오. */ Orc a = new Orc("오크",80); System.out.println(a.toString()); /* 2. OrcWarrior 객체를 만들고 정보를 출력하시오. */ OrcWarrior b = new OrcWarrior("오크전사",120,3); System.out.println(b.toString()); } } class Orc { protected String name; protected int hp; public Orc(String name, int hp) { this.name = name; this.hp = hp; } public String toString() { return String.format("Orc { name: %s, hp: %d }", this.name, this.hp); } } class OrcWarrior extends Orc { protected int amor; public OrcWarrior(String name, int hp, int amor) { super(name, hp); this.amor = amor; } // 메소드 오버라이딩! public String toString() { return String.format("OrcWarrior { name: %s, hp: %d, amor: %d }", super.name, super.hp, this.amor); // 부모 크래스에 있는 super 를 씀 } } |
Orc { name: 오크, hp: 80 } OrcWarrior { name: 오크전사, hp: 120, amor: 3 } |
import java.util.ArrayList; // 리팩토링(코드를 조금더 깔끔하고 이해하기 쉽게 개선하는 작업 ) public class ElvesTest { public static void main(String[] args) { // 앨프 객체 생성 & 업캐스팅 (부모 타입으로 해석) Elf a = new Elf("티란데",100); Elf b =new HighElf("알퓨리온",160,100); Elf c = new ElfLord("마이에브",230,140,100); // 객체 배열 생성 => ArrayList로 묶기! ArrayList<Elf> list = new ArrayList<Elf>(); list.add(a); list.add(b); list.add(c); // 반복을 통한 출력 for (int i =0; i < list.size(); i++){ // System.out.println(elves[i].toString()); System.out.println(list.get(i).toString()); } } } class Elf{ 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",this.name,this.hp); } } class HighElf extends Elf{ // name ,hp 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",super.name,super.hp,this.mp); } } class ElfLord extends HighElf{ // name, hp ,mp protected int shield; public ElfLord(String name, int hp, int mp, int shield){ super(name,hp,mp); // 부모 생성자 호출 !! this.shield = shield; } // 메소드 오버라이딩! (재정의) public String toString(){ return String.format("[엘프로드] Name: %s, HP:%d, mp:%d, SH: %d",super.name,super.hp,super.mp,this.shield); } } |
- 출력
[엘프] Name: 티란데, HP:100 [하이엘프] Name: 알퓨리온, HP:160, mp:100 [엘프로드] Name: 마이에브, HP:230, mp:140, SH: 100 |
출저: 홍팍 (https://www.youtube.com/@hongpark)
이 블로그 기록은 개인 공부용 기록입니다.