본문 바로가기
프로그래밍 언어/java

[java] 상속, 생성과정

by m2162003 2021. 3. 9.

상속이란

이미 있는 클래스를 확장하기 위해 사용한다.

보통 상위 클래스는 하위 클래스보다 일반적인 개념과 기능을 가지고,  하위 클래스는 상위클래스보다 구체적인 개념과 기능을 가지게 설계한다.

 

자바는 sigle inheritance, 하나의 상속만 가능하다.

extends뒤에 한 개의 클래스만 올 수 있다는 뜻이다.

 

예시:

일반 고객과 vip 고객

전자를 상위 클래스, 후자를 하위 클래스로 설정한다.

public class Customer {
	private int customerID;
	protected String customerName;
	protected String customerGrade;
	
	int bonusPoint;
	double bonusRatio;
}

public class VIPCustomer extends Customer{
	double salesRatio;
	private int agentID;
}

 

VIPCustomer는 Customer에 있는 멤버 변수들을 기본적으로 가지고 있고 추가로 salesRatio와 agentID를 가지고 있다.

 

 

protected 접근제한자

private으로 접근제한을 걸면 하위 클래스를 포함한 모든 클래스에서 접근이 불가능하다.

상속받은 하위 클래스만 접근 가능하게 하고 싶다면 protected를 사용한다.

 

위의 예시에서도 고객 이름과 고객 등급은 접근 가능하게 만들어놨다. 

 

 

하위 클래스 생성 과정

하위 클래스가 생성될 때 상위 클래스가 먼저 생성된다.

따라서 상위 클래스 생성자 -> 하위 클래스 생성자 순으로 호출이 되기 때문에 하위 클래스 생성자에서는 상위 클래스 생성자를 호출해야 한다.

 

super()

super()은 상위 클래스 기본 생성자이다.

컴파일 단계에서 하위 클래스 생성자 호출 시 자바가 자동으로 super()를 추가해준다. 이 경우 사용자가 직접 코드를 적지 않아도 된다.

하지만 상위 클래스에 기본 생성자가 없다면?? 사용자가 super()에 인자를 넣어서 직접 호출을 해줘야 한다.

 

//상위 클래스
public class Customer {
	private int customerID;
	protected String customerName;
	protected String customerGrade;
	
	int bonusPoint;
	double bonusRatio;
	
    // 상위 클래스 기본 생성자 
	public Customer() {
		customerGrade =  "SILVER";
		bonusRatio = 0.01;
		
		System.out.println("Customer() 생성자 호출");
	}
    
}


//하위 클래스 
public class VIPCustomer extends Customer{
	double salesRatio;
	private int agentID;
	
	public VIPCustomer(int customerID, String customerName) {
		customerGrade = "VIP";
		
		bonusRatio = 0.05;
		salesRatio = 0.1;
		System.out.println("VIP 생성자 호출");
	}

}

 

public class CustomerTest {
	public static void main(String[] args) {
		VIPCustomer cKim = new VIPCustomer(10020, "아이유");		
	}
}
 

 

실행 결과

customer의 기본 생성자가 호출 된 것을 확인할 수 있다. 

저기서 customer의 기본 생성자를 주석 처리하면 에러가 발생한다. 

 

custom 생성자를 추가해보자.

public class Customer {
	private int customerID;
	protected String customerName;
	protected String customerGrade;
	
	int bonusPoint;
	double bonusRatio;
	
	public Customer() {
		customerGrade =  "SILVER";
		bonusRatio = 0.01;
		
		System.out.println("Customer() 기본생성자 호출");
	}
	
	public Customer(int customerID, String customerName) {
		customerGrade =  "SILVER";
		bonusRatio = 0.01;
		
		this.customerID = customerID;
		this.customerName = customerName;
		
		System.out.println("Customer() custom 생성자 호출");
	}
}
public class VIPCustomer extends Customer{
	double salesRatio;
	private int agentID;
	
	public VIPCustomer(int customerID, String customerName) {
		
		super(customerID, customerName); //상위클래스 생성자 명시
		customerGrade = "VIP";
		
		bonusRatio = 0.05;
		salesRatio = 0.1;
		System.out.println("VIP 생성자 호출");
	}
}
public class CustomerTest {
	public static void main(String[] args) {
		VIPCustomer cKim = new VIPCustomer(10020, "아이유");
	}
}
 

실행결과

 

 

상속에서의 메모리 상태

상위 클래스 인스턴스가 먼저 생성되고 하위 클래스 인스턴스가 생성된다.

클래스 인스턴스는 힙!!에 생성된다. 

 

댓글