스퐁지송 개발노트

22.11.29 본문

JAVA 입문 시작

22.11.29

강준석 2022. 11. 29. 11:36
728x90

어제 하던 다형성 이어서 하기

 

 

 

업캐스팅과 다운캐스팅

 

Parent p = new Parent()

Parent p = new Child(); // 업캐스팅

p.run();

Child c = (Child)p; //다운캐스팅

c.eat();

예시)

 

예시2)

 

결과: 

기본 공격을 합니다
마법사가 기본 공격을 합니다
기사가 기본 공격을 합니다

 

 

지금까지 배운걸로 TV만들기,.................

 

부모문

 

 

package TV만들기;

import org.omg.CORBA.PUBLIC_MEMBER;

public class PrototypeTV {

	boolean isPower; // 전원 on,off
	int channel; // 채널
	int volume; // 볼륨

	public PrototypeTV() {
		isPower = false;
		channel = 10;
		volume = 10;
	}

	public PrototypeTV(boolean isPower, int channel, int volume) {

		this.isPower = isPower;
		this.channel = channel;
		this.volume = volume;
	}

	public void setChannel(int cnl) {

		if (cnl >= 0 && cnl < 1000) {
			channel = cnl;
		} else {
			System.out.println("채널이 없습니다");
		}
	}

	

}

 

 

자식문

 

 

package TV만들기;

public class TV extends PrototypeTV {

	String name;
	boolean isInternet;

	TV() {
		super();
		name = "LG TV";
		isInternet = false;

	}

	TV(String name) {
		super(false, 20, 15);
		this.name = name;
		isInternet = false;

	}

	void setPower(boolean isPower) {
		this.isPower = isPower;
	}

	public void setChannel(int cnl) {
		if (cnl >= 0 && cnl < 2000) {
			channel = cnl;
		} else {
			System.out.println("채널이 없습니다.");
		}

	}

	public void setChannel(int cnl, boolean isInternet) {
		if (isInternet) {
			System.out.println("인터넷 연결 성공");
			this.isInternet = true;
		} else {
			this.isInternet = false;
			if (cnl >= 0 && cnl < 2000) {
				channel = cnl;
				System.out.println("채널이" + channel + "로 변경");
			} else {
				System.out.println("채널이 없습니다[0~2000]");
			}
		}
	}

	public void setVolume(int vol) {
		if (vol >= 0 && vol <= 100) {
			volume = vol;
		} else {
			System.out.println("볼륨 범위 벗어남[0~100]");
		}
	}

	public void viewTV() {
		System.out.println("이름 : " + name);
		System.out.println("전원 : " + isPower);
		System.out.println("채널 : " + channel);
		System.out.println("볼륨 : " + volume);
		System.out.println("인터넷 연결 : " + isInternet);

	}
}

 

 

메인 출력문

 

 

package TV만들기;

public class Main {

	public static void main(String[] args) {
		
		TV lgTV=new TV();
		
		lgTV.viewTV();
		
		lgTV.setPower(true);
		lgTV.setChannel(100);
		System.out.println("-----------");
		
		lgTV.viewTV();
		
		
		
		lgTV.setChannel(222,true);
		
		lgTV.setChannel(9999,false);
		lgTV.setVolume(12312313);
		

	}

}

개빡친다;;

728x90

'JAVA 입문 시작' 카테고리의 다른 글

22.11.29 final 클래스  (0) 2022.11.29
22.11.29 추상 클래스 (메서드)  (0) 2022.11.29
22.11.28 매서드 재정의  (1) 2022.11.28
22.11.28 상속이란...  (0) 2022.11.28
11.26  (0) 2022.11.28
Comments