IT/자바

생성자 초기화 순서

Beautifulkim 2018. 5. 3. 15:01

MyMain_Super.java

Parent.java

Child.java

package mymain;

import myutil.Child;

public class MyMain_Super {

	public static void main(String[] args) {
		/*
			Child(); 생성자 자식꺼 호출 -> 
			Parent(); 생성자 부모꺼 호출 -> 
			Object(); 생성자 Object꺼 호출

			처리순서(초기화순서) 
			1. 오브젝트 > 
			2. 부모호출 > 
			3 자식호출
		 */
		Child child = new Child();
		child.display_total_money();
		
		Child child2 = new Child(100000, 200000);
		child2.display_total_money();
	}
}
package myutil;

public class Parent {
	//protected : 자식에게 물려주기 위해
	protected int parent_money;
	
	public Parent() {
		super();// Object();
		parent_money = 1000;
		System.out.println("--Parent()--");
	}

	public Parent(int parent_money) {
		super();
		this.parent_money = parent_money;
		System.out.println("--Parent(int)--");
	}
}
package myutil;

public class Child extends Parent {

	//상속받은 자식에게 사용 가능하게 하기위해 protected
	//child_money의 금액 = child_money + parent_money
	protected int child_money;
	
	public Child() {
		//super();//묵시적으로 생략된 형태(생략되면 묵시적 처리)
				//Parent() Call
		child_money = 10000;
		System.out.println("--Child()--");
	}
	
	public Child(int parent_money, int child_money) {
		/*
		아래처럼 초기화해도 상관은 없지만 문제가 생기므로 
		super(parent)를 써서 아버지가 직접 초기화하게 만듬

		super.parent_money = parent_money;
		*/
		
		//아버지가 직접 초기화 하게됨
		super(parent_money);// Parent(int) Call
		this.child_money = child_money;
		System.out.println("--Child(int p, int c)--");
	}
	
	public void display_total_money () {
		System.out.printf(
				"아버지(%d)+자식(%d)=총액(%d)\n",
				super.parent_money,
				this.child_money,
				super.parent_money+this.child_money
		);
	}	
}