-
3. OOP(Object Oriented Programming) 오버라이딩프로그래밍언어/Java(초급) 2020. 4. 7. 01:49
안녕하세요 현우입니다. 이번 포스팅은 [ OOP 상속 - 오버라이딩의 이해 및 사용 ] 입니다.
참고도서
http://www.orentec.co.kr/teachlist/JAVA_BASIC_1/teach_sub1.php
1. 상속을 위한 기본 조건인 IS-A 관계의 성립
상속의 기본 문법에서 보이듯이, 하위 클래스는 상위 클래스가 지니는 모든 것을 지니고, 하위클래스만의 추가적인 특징이 더해진다.
예시)
- 전화기 -> 무선 전화기
- 컴퓨터 -> 노트북 컴퓨터
컴퓨터와 전화기의 기본기능은 각각 '통화'와 '계산'이다. 그런데, 무선 전화기와 노트북은 '이동성' 이라는 특성이 추가 되었다. 따라서 전화기와 컴퓨터를 상위 클래스로, 무선전화기와 노트북 컴퓨터를 각각의 하위클래스로 정의 하였다.
이러한 상속관계가 성립되면
- 무선 전화기도 일종의 전화기 이다
- 노트북 컴퓨터도 일종의 컴퓨터 이다
- 무선 전화기 is a 전화기
- 노트북 컴퓨터 is a 컴퓨터
위의 조건이 만족된다. 즉 상속관계가 성립되려면 상위 클래스와 하위클래스의 관계가 IS - A 관계가 성립해야 한다.
- IS-A 관계
코드예제 class Computer { String owner; public Computer(String name){owner=name;} public void calculate() { System.out.pringln("요청 내용을 계산합니다.");} } class NotebookComp extends Computer { int battery; public NotebookComp(String name, int initChag) { super(name); //상위클래스 생성자를 생성하면서 매개변수를 지정한다. battery=initChag; //배터리값 초기화 } public void charging() { battery+=5;} // 배터리 5%충전 public void movingCal() { if(battery<1) //배터리가 1% 미만일경우 { System.out.print("충전이 필요합니다."); return; } System.out.print("이동하면서 "); calculate(); battery-=1; } } class TabletNotebook extends NotebookComp { String regstPenModel; public TabletNotebook(String name, int initChag, String pen){ super(name, initChag); regstPenModel=pen; } public void write(String penInfo) { if(battery<1) { System.out.println("충전이 필요합니다."); return; } } if(regstPenModel.compareTo(penInfo)!=0) { System.out.println("등록된 펜이 아닙니다."); return; } System.out.prinln("필기 내용을 처리합니다."); battery-=1; //글등록시 배터리 차감 } } class ISAInheritance { public static void main(Strimg[] args) { NotebookComp nc = new NotebookComp("이수종", 5); TableNotebook tn = new TabletNotebook("정수영",5,"ISE-241-242"); nc.movingCal(); //이동 tn.write("ISE-241-242"); //펜탑재 } }
- NotebookComp는 Computer이다
- TabletNotebook은 NotebookComp이다.
- TabletNotebook는 Computer이다.
때문에 IS-A 관계의 관점에서만 보면 위 클래스들의 상속관계는 적절했다고 볼 수 있다. IS-A외에도 HAS-A관계도 상속의 조건이 된다. 즉 하위클래스는 상위클래스가 지니고 있는 모든것을 소유한다.
- HAS-A관계
class Gun { int bullet; public Gun(int bnum) { bullet= bnum;} public void shot() { System.out.println("BBANG!"); bullet--; } } class Police extends Gun { int handcuffs; public Police(int bnum, int bcuff){ super(bunm); handcuffs=bcuff; } public void putHandcuff(){ System.out.println("SNAP!"); handcuffs--; } } class HASInheritance { public static void main(String[] args) { Police pman = new Police(5,3); pman.shot(); pman.putHandcuff(); } }
위 예제에서 경찰은 권총을 소유하고 있다 즉 경찰 has a 총 이 된다. 즉 HAS-A관계도 상속으로 표현할 수 있다.
2. 오버라이딩
상위클래스에 정의된 메소드 이름, 반환형, 매개변수 선언까지 완전히 동일한 메소드를 하위클래스에서 다시 정의 한다.
class Speaker { private int volumeRate; public void showCurretnState() { System.out.print("볼륨 크기 : " +volumeRate); } public void setVolume(int vol) { volumeRate=vol; } } class BaseEnSpeaker extends Speaker { private int baseRate; public void showCrrentState() //상위클래스 메소드 재정의 { super.showCurrentState(); //super를 이용하여 상위클래스에 정의된 함수를 호출한다 System.out.print("베이스 크기 :" +baseRate); } } public void setBaseRate(int base) { baseRate= base; } } class Overriding { public static void main(String[] args) { BaseEnSpeaker bs = new BaseEnSpeaker(); bs.setVolume(10); bs.setBaseRate(20); bs.showCurrentState(); } }
'프로그래밍언어 > Java(초급)' 카테고리의 다른 글
2. OOP(Object Oriented Programming) 상속 (0) 2020.04.02 1. OOP(Object Oriented Programming) 캡슐화 (0) 2020.04.01 5. Collection 프레임워크 (ArrayList vs LinkedList) (0) 2020.03.29 4. StringBuilder & StringBuffer 클래스 다루기 (0) 2020.03.27 3. Java 문자열(String) 다루기 (0) 2020.03.27