반응형
package overriding;

public class CellPhone {
		//필드
		String model;
		String color;
		
		// 메소드
		void powerOn() { System.out.println("전원을 켭니다.");}
		void bell() { System.out.println("벨이 울립니다.");}
		void sendVoice(String message) {System.out.println("자기 : " + message);}
		void receiveVoice(String message) { System.out.println("상대방 : " + message);}
		void hangUp() {System.out.println("전화를 끊습니다.");}
		void powerOff() { System.out.println("전원을 끕니다.");}
}
package overriding;

public class DmbCellPhone extends CellPhone{
	int channel;
	// 생성자
	DmbCellPhone(String model, String color , int channel){
		this.model = model;
		this.color = color;
		this.channel = channel;
	}
	
	//메소드
	
	void turnOnDmb() {
		System.out.println("채널 " + channel + " 번 DMB 방송 수신을 시작합니다.");
	}
	void changeChannelDmb(int channel) {
		this.channel = channel;
		System.out.println("채널 " + channel + "번으로 바꿉니다");
	}
	void turnOffDmb() {
		System.out.println("DMB 방송 수신을 멈춥니다.");
	}
}
​
package overriding;

public class DmbCellPhoneExam {

	public static void main(String[] args) {
		//DmbCellPhone 객체 생성
		DmbCellPhone dmbCellPhone = new DmbCellPhone("자바폰","검정",10);
		
		//CellPhone으로부터 상속 받은 필드
		System.out.println("모델 " + dmbCellPhone.model);
		System.out.println("색상 " + dmbCellPhone.color);
		
		//DmbCellPhone의 필드
		System.out.println("채널 " + dmbCellPhone.channel);
		System.out.println();

		//CellPhone으로부터 상속 받은 메소드 호출
		dmbCellPhone.powerOn();
		dmbCellPhone.bell();
		dmbCellPhone.sendVoice("여보세요");
		dmbCellPhone.receiveVoice("안녕하세요! 저는 홍길동인데요");
		dmbCellPhone.hangUp();
		System.out.println();
		
		//DmbCellPhone의 메소드 호출
		dmbCellPhone.turnOnDmb();
		dmbCellPhone.changeChannelDmb(12);
		dmbCellPhone.turnOffDmb();

	}

}

상속이라는게 부모가 자식한테 재산 등을 물려줄 때 일반적으로 사용하는 말이죠?

똑같습니다. 여기에서는 CellPhone이라는 부모한테 DmbCellPhone이 물려받는 것입니다.

CellPhone이 더 큰 범위이기 때문에 부모인거죠

 

이렇게 쓰면 장점이 CellPhone의 기능 몇개는 DmbCellPhone과 겹치는데 하나하나씩 입력하기 힘듭니다.

(전화기능 , 문자기능 등...)

코드를 간략하게 할 수 있습니다.

 

상속받는 방법 public class (내가 만든 클래스명) extends (부모 클래스명)입니다.

여기서는 public class DmbCellPhone extends CellPhone 가 되는 거죠

 

그러면 DmbCellPhone은 CellPhone의 변수와 메소드를 전부 사용할 수 있게 됩니다.

 

https://github.com/SungJLee/My_Java_World.git

 

SungJLee/My_Java_World

Contribute to SungJLee/My_Java_World development by creating an account on GitHub.

github.com

 

반응형