- Do it! 자바 프로그래밍 입문 온라인 강의를 수강하며 작성하였습니다.
- Section 1. 자바의 핵심 - 객체지향 프로그래밍
- 23강 "상속과 다형성(2)"
- 접근 제한자 가시성 > 상속에서 클래스 생성 과정 > 상속에서의 메모리 상태 > super 예약어 > 상위 클래스로의 묵시적 형변환 (업캐스팅)
지난 강의에서 사용한 Customer 클래스와 VIPCustomer 클래스를 수정하면서 강의가 진행된다.
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;
}
}
외부 클래스 | 하위 클래스 | 동일 패키지 | 내부 클래스 | |
---|---|---|---|---|
public | O | O | O | O |
protected | X | O | O | O |
선언되지 않음 (default) | X | X | O | O |
private | X | X | X | O |
Customer 클래스의 기본 생성자와 VIPCustomer 클래스의 기본 생성자에 출력문을 추가하여 확인해보자.
public class Customer {
Customer(){
System.out.println("Customer() 호출");
}
}
public class VIPCustomer extends Customer{
public VIPCustomer() {
System.out.println("VIPCustomer() 호출");
}
}
main 함수가 있는 CustomerTest 클래스에서 VIPCustomer 객체를 생성하여 출력해보면 상위 클래스인 Customer 클래스의 생성자가 먼저 호출된 것을 확인할 수 있다.
public class CustomerTest {
public static void main(String[] args) {
VIPCustomer customerKim = new VIPCustomer();
}
}
즉, 위 코드에서 VIPCustomer 클래스의 생성자에는 super() 를 자동으로 호출해준 것이다.
Customer 클래스의 생성자도 super() 가 자동으로 호출되는데, java의 최상위 클래스인 Object 클래스의 생성자가 호출된 것이다.
public class VIPCustomer extends Customer{
public VIPCustomer() {
super();
System.out.println("VIPCustomer() 호출");
}
}
Customer 클래스의 기본 생성자를 없애고, 매개변수를 받는 constructor를 만들어준다면 VIPCustomer 클래스의 생성자에서는 Super(매개변수)를 통해 생성자를 호출해주어야 한다.
public class Customer {
Customer(int customerID, String customerName){
this.customerID = customerID;
this.customerName = customerName;
System.out.println("Customer(int, String) 호출");
}
}
public class VIPCustomer extends Customer{
public VIPCustomer() {
super(1001, "이순신");
System.out.println("VIPCustomer() 호출");
}
public VIPCustomer(int customerID, String customerName) {
super(customerID, customerName);
System.out.println("VIPCustomer(int, String) 호출");
}
}
위 코드에서 vc는 VIPCustomer() 생성자를 호출했으므로 인스턴스는 모두 생성된다.
하지만 타입이 Customer 이므로 접근할 수 있는 변수나 메서드는 Customer 클래스의 변수와 메서드이다.