– 클래스 상속
자바에서 상속(Inheritance)은 객체 지향 프로그래밍의 핵심 개념 중 하나로, 새로운 클래스가 기존 클래스의 특성과 동작을 물려받는 것을 의미합니다. 상속을 통해 코드의 재사용성을 높이고, 계층 구조를 통해 코드를 조직화할 수 있습니다.
상속에서 기존의 클래스는 부모 클래스(또는 상위 클래스, 슈퍼 클래스)라고 하며, 새로운 클래스는 자식 클래스(또는 하위 클래스, 서브 클래스)라고 합니다. 자식 클래스는 부모 클래스의 필드와 메서드를 상속받아 사용할 수 있으며, 필요에 따라 이를 재정의(오버라이딩)하거나 확장할 수 있습니다.
- 새로운 클래스를 정의 할 때 이미 구현된 클래스 상속(inheritance) 받아서 속성이나 기능을 확장하여 클래스를 구현함
- 이미 구현된 클래스보다 더 구체적인 기능을 가진 클래스를 구현해야 할 때 기존 클래스를 상속함
– 상속을 구현 하는 경우
- 상위 클래스는 하위 클래스 보다 더 일반적인 개념과 기능을 가짐
- 하위 클래스는 상위 클래스 보다 더 구체적인 개념과 기능을 가짐
- 하위 클래스가 상위 클래스의 속성과 기능을 확장(extends)한다는 의미
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 * bonusRatio;
return price;
}
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 String showCustomerInfo(){
return customerName + "님의 등급은" + customerGrade + "이며, 보너스 포인트는"
+ bonusPoint + "입니다.";
}
}
public class VIPcustomer extends Customer {
protected int agentID;
double salesRatio;
public VIPcustomer(){
customerGrade = "VIP";
salesRatio = 0.05;
bonusRatio = 0.1;
}
public int getAgentID(){
return agentID;
}
}
public class CustomerTest {
public static void main(String[] args) {
Customer customerLee = new Customer();
customerLee.setCustomerName("이순신");
customerLee.setCustomerId(10010);
customerLee.bonusPoint = 1000;
System.out.println(customerLee.showCustomerInfo());
VIPcustomer vipCustomerKim = new VIPcustomer();
vipCustomerKim.setCustomerName("김유신");
vipCustomerKim.setCustomerId(10020);
vipCustomerKim.bonusPoint = 10000;
System.out.println(vipCustomerKim.showCustomerInfo());
}
}
– 상속에서 클래스 생성 과 형변환
자바에서 클래스 생성 시 상속을 통해 부모 클래스의 속성과 메서드를 자식 클래스에 물려받을 수 있습니다. 자식 클래스의 인스턴스를 생성하면, 부모 클래스의 생성자가 먼저 호출되고 나서 자식 클래스의 생성자가 호출됩니다. 이를 통해 자식 클래스는 부모 클래스의 초기화 과정을 상속받게 됩니다.
- 하위 클래스를 생성하면 상위 클래스가 먼저 생성 됨
- new VIPCustomer()를 호출하면 Customer()가 먼저 호출 됨
- 클래스가 상속 받은 경우 하위 클래스의 생성자 에서 는 반드시 상위 클래스의 생성자를 호출 함
– super 키워드
자식 클래스의 생성자에서 명시적으로 부모 클래스의 생성자를 호출하고자 할 때는 super()를 사용합니다. super()는 반드시 자식 클래스 생성자의 첫 번째 줄에 위치해야 합니다.
- 하위 클래스에서 가지는 상위 클래스에 대한 참조 값
- super()는 상위 클래스의 기본 생성자를 호출 함
- 하위 클래스에서 명시적으로 상위 클래스의 생성자를 호출하지 않으면 super()가 호출 됨 (이때 반드시 상위 클래스의 기본 생성자가 존재 해야 함)
- 상위 클래스의 기본 생성자가 없는 경우 (다른 생성자가 있는 경우) 하위 클래스에서는 생성자 에서 는 super를 이용하여 명시적으로 상위 클래스의 생성자를 호출 함
- super는 생성된 상위 클래스 인스턴스의 참조 값을 가지므로 super를 이용하여 상위 클래스의 메서드나 멤버 변수에 접근할 수 있음
– 형변환 (Type Casting)
자바에서는 클래스 간 상속 관계에서 형변환을 통해 객체를 다른 타입으로 변환할 수 있습니다. 형변환은 크게 업캐스팅(Upcasting)과 다운캐스팅(Downcasting)으로 나눌 수 있습니다.
– 업캐스팅 (Upcasting)
업캐스팅은 자식 클래스의 객체를 부모 클래스 타입으로 변환하는 것입니다. 업캐스팅은 암시적으로 수행되며, 특별한 문법이 필요하지 않습니다.
– 다운캐스팅 (Downcasting)
다운캐스팅은 부모 클래스 타입의 객체를 자식 클래스 타입으로 변환하는 것입니다. 다운캐스팅은 명시적으로 수행되어야 하며, 문법적으로 (타입)을 사용합니다.
public class Customer {
protected int customerId;
protected String customerName;
protected String customerGrade;
int bonusPoint;
double bonusRatio;
// public Customer(){
// customerGrade = "SILVER";
// bonusRatio = 0.01;
// System.out.println("Customer() Call");
// }
public Customer(int customerId, String customerName){
this.customerId = customerId;
this.customerName = customerName;
customerGrade = "SILVER";
bonusRatio = 0.01;
System.out.println("Customer(int, String) Call");
}
public int calcPrice(int price){
bonusPoint += price * bonusRatio;
return price;
}
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 String showCustomerInfo(){
return customerName + "님의 등급은" + customerGrade + "이며, 보너스 포인트는"
+ bonusPoint + "입니다.";
}
}
public class VIPcustomer extends Customer {
protected int agentID;
double salesRatio;
public VIPcustomer(int customerId, String customerName){
super(customerId, customerName);
customerGrade = "VIP";
salesRatio = 0.05;
bonusRatio = 0.1;
System.out.println("VIPcustomer(int, String) Call");
}
public int getAgentID(){
return agentID;
}
}
public class CustomerTest {
public static void main(String[] args) {
// Customer customerLee = new Customer();
// customerLee.setCustomerName("이순신");
// customerLee.setCustomerId(10010);
// customerLee.bonusPoint = 1000;
//
// System.out.println(customerLee.showCustomerInfo());
VIPcustomer vipCustomerKim = new VIPcustomer(10020,"김유신");
vipCustomerKim.bonusPoint = 10000;
System.out.println(vipCustomerKim.showCustomerInfo());
}
}
잘~보구갑니다잉?