티스토리 뷰

반응형

25. 상속이란 - 1

| 클래스에서 상속의 의미

새로운 클래스를 정의할 때, 이미 구현된 클래스를 상속받아서 속성이나 기능이 확장되는 클래스를 구현함.

( 다중 상속이 안되는 자바)

 

 

| 상속을 사용하는 경우

상위 클래스는 하위 클래스보다 일반적인 개념과 기능을 가짐

하위 클래스는 상위 클래스보다 구체적인 개념과 기능을 가짐

 

extends 뒤에는 단 하나의 class 만 사용할 수 잇음.

자바는 single inheritance 만을 지원함.

 

 

 

 

26. 상속이란 - 2

 

| protected 예약어

 

외부클래스에선private ,   하위 클래스에는 public 의 기능을 구현한 키워드.

사우이 클래스에 protected로 선언된 변수나 메서드는 다른 외부 클래스에서는 사용할 수 없지만, 하위 클래스에서는 사용가능

 

package inheritance;

public class CustomerTest {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Customer customerLee = new  Customer();
		customerLee.setCustomerName("이순신");
		customerLee.setCustomerID(1001);
		customerLee.bonusPoint=1000;
		System.out.println(customerLee.showCustomerInfo());
		
		Customer customerKim = new  VIPCustomer();
		customerKim.setCustomerName("김유신");
		customerKim.setCustomerID(1002);
		customerKim.bonusPoint=120000;
		System.out.println(customerKim.showCustomerInfo());
	}

}
package inheritance;

public class Customer {

	protected int customerID;
	protected String customerName;
	protected String customerGrade; // 자식이 쓸수 있게 p rotected
	int bonusPoint;
	double bonusRatio;

	public Customer() {
		customerGrade = "SILVER";
		bonusRatio = 0.01;
	}

	public int calcPrice(int price) {
		bonusPoint += price * bonusRatio;
		return price;
	}

	public String showCustomerInfo() {
		return customerName + "님의 등급은 " + customerGrade + "이고, 적립된 보너스 포인트는 " + bonusPoint + "점 입니다.";
	}

	public int getCustomerID() {
		return customerID;
	}

	public void setCustomerID(int customerID) {
		this.customerID = customerID;
	}

	public String getCustomerName() {
		return customerName;
	}

	public void setCustomerName(String customerName) {
		this.customerName = customerName;
	}

	public String getCustomerGrade() {
		return customerGrade;
	}

	public void setCustomerGrade(String customerGrade) {
		this.customerGrade = customerGrade;
	}

}

 

package inheritance;

public class VIPCustomer extends Customer {
	
	
	
	private int agentID;
	double salesRatio;
	
	public VIPCustomer() {
		customerGrade = "Gold";
		bonusRatio = 0.05;
		salesRatio = 0.1;
	}

}

 

바 인강이 듣고 싶다면 => https://bit.ly/3ilMbIO

반응형
댓글
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2025/02   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28
글 보관함