기록장

상속에 대해서 설명해줄게 본문

개발/JAVA

상속에 대해서 설명해줄게

HJJJJJ 2022. 5. 16. 17:24
728x90

간단해 물려주는걸 상속이라고 해  

 

프로그램에서는 자식이 부모를 선택하는거야 선택된 부모 클래스는 extends를 앞에 붙여

자식클래스 extends 부모클래스 {
//필드
//생성자
//메소드
}

 

package sec03.exam01;

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

이건 부모클래스 만들었어

package sec03.exam01;

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 sec03.exam01;

public class DmbCellPhoneExample {

	public static void main(String[] args) {
		//DMBCellPhone 객체 생성
		DmbCellPhone dmbCellPhone = new DmbCellPhone("자바폰","검정",10);
		
		//CellPhone 클래스의 필드
		System.out.println("모델:"+ dmbCellPhone.model);
		System.out.println("색상:"+ dmbCellPhone.model);

		
		//DmbCellPhone
		System.out.println("채널:"+dmbCellPhone.channel);
		
		//CellPhone 클래스로부터 상속받은 메소드 호출
		dmbCellPhone.powerOn();
		dmbCellPhone.bell();
		dmbCellPhone.sendVoice("여보세요");
		dmbCellPhone.reciveVoice("안녕하세요 저는 홍길동인데요");
		dmbCellPhone.sendVoice("아~예 반갑습니다");
		dmbCellPhone.hangUp();
		
		//DmbCellPhone 클래스의 메소드 호출
		dmbCellPhone.turnOnDMb();
		dmbCellPhone.changeChannelDMb(12);
		dmbCellPhone.turnOffDmb();
		
		
	}
	}

}

이건 자식 클래스의 사용이야 

 


 

package sec03.exam01;

public class People {
	public String name;
	public String ssn;
	
	public People(String name, String ssn) {
		this.name = name;
		this.ssn = ssn;
	}

}
package sec03.exam01;

public class Student extends People {
	public int studentNo;
	
	public Student(String name, String ssn, int studentNo) {
		super(name, ssn);
		this.studentNo = studentNo;
	}
}
package sec03.exam01;

public class StudentExample {

	public static void main(String[] args) {
		Student student = new Student("홍길동","123456-12334567", 1);
		System.out.println("name:"+student.name);
		System.out.println("ssn"+student.ssn);
		System.out.println("studentNo:"+student.studentNo);
		

	}

}
728x90
Comments