- Do it! 자바 프로그래밍 입문 온라인 강의를 수강하며 작성하였습니다.
- Section 1. 자바의 핵심 - 객체지향 프로그래밍
- 22강 "상속과 다형성(1)"
- 상속이란? > 상속을 활용한 고객관리 프로그램
//클래스 상속 문법
class B extends A{
code...
}
public class Piont{
private int x;
private int y;
public int getX(){
return x;
}
public void setX(int x){
this.x = x;
}
public int getY(){
return x;
}
public void setY(int y){
this.y = y;
}
}
x와 y 값을 갖는 Point라는 클래스가 있다고 하자.
이 때, 중심(점)과 반지름을 갖는 Circle 클래스를 만든다면 Circle 클래스는 Point 클래스를 상속받는 것이 아니라 객체를 생성해서 변수에 넣어주면 된다.
//잘못된 코드
public Circle extends Point{
private int radius;
}
//권장되는 코드
public Circle {
Point point;
private int radius;
public Circle(){
point = new Point();
}
}
Point 클래스가 일반적이고, Circle 클래스가 구체적인 관계가 아니기 때문에 상속 관계가 아닌 것이다.
멤버 변수 | 설명 |
---|---|
customerID | 고객 아이디 |
customerName | 고객 이름 |
customerGrade | 고객 등급 기본 생성자에서 지정되는 기본 등급은 SILVER |
bonusPoint | 고객의 보너스 포인트 고객이 제품을 구매할 경우 누적되는 보너스 포인트 |
bonusRatio | 보너스 포인트 적립 비율 고객이 제품을 구매할 때 보너스 포인트로 적립될 적립 비율 기본 생성자에서 지정되는 적립 비율은 1% |
public class Customer {
protected int customerID;
protected String customerName;
protected String customerGrade;
int bonusPoint;
double bonusRatio;
public Customer() {
customerGrade = "SILVER";
bonusRatio = 0.01;
}
public int calcPrice(int price) {
bonusPoint += price * bonusPoint;
return price;
}
public void showCustomerInfo() {
System.out.println(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;
}
}
public class VIPCustomer extends Customer{
private int agentID;
private double saleRatio;
public VIPCustomer() {
customerGrade = "VIP";
bonusRatio = 0.05;
saleRatio = 0.1;
}
public int getAgentID() {
return agentID;
}
}
child class는 parent class를 그대로 복사해와서 사용하므로 중복되는 변수나 메서드는 다시 선언할 필요가 없다.
- potected 로 변수를 선언하면 상속받는 클래스에서 해당 변수에 접근할 수 있다.
(다른 패키지에 있어도 접근 가능)- public 으로 선언하면 어디서든 접근 가능
- private 으로 선언하면 해당 클래스 내부에서만 접근 가능
- 아무런 선언도 하지 않으면 (default) 같은 패키지 내에서 접근 가능