본문 바로가기
  • 문과생의 백엔드 개발자 성장기
|Developer_Study/정보처리기사

[정보처리기사] JAVA 2 (생성자)

by 케리's 2023. 3. 14.

01. 생성자

1. 예제

class Parent{

	int age=30; // 멤버변수
	String name="ila";

    public Parent(){ // 생성자 (3)
		System.out.println("부모 디폴트 생성자");
    }


	public Parent(int age, String name) { 
		this.age=age;
		this.name=name;
		System.out.println("부모 인자 있는 생성자");
	}

	public void print() { //메서드
		System.out.println(name+", "+age);
	}
}

class Child extends Parent{ // 부모를 상속받음
	public Child(int age, String name) { // (2) 자식 생성자(디폴트 생성자는는 없음), 
    	// 자식은 부모로부터 상속을 받았기 때문에 무조건 부모의 디폴트 생성자를 탄다. 
		// (만약 super로 명시되어있으면 super가 명시한 부모의 생성자를 탄다)
        // (5)
        System.out.println("자식 생성자");  //(4)
	}

	public static void main(String[] args) {
		Child a = new Child(25,"ila2"); // (1) 자식형태의 생성자를 탄다. 왜냐 Child a로 선언해서
		a.print(); // 자식에게 print 메서드가 없음, 때문에 부모의 메서드를 탄다. 그러나 자식의 인자를 대입하는 곳이 없기 때문에 부모의 인자를 출력한다. 
	}
}
// ===== 출력 결과
// 부모 디폴트 생성자
// 자식 생성자
// ila 30

// 만약 ila2 25를 출력하려면 ?? 
// (5)번에 super(age,name); 으로 인자있는 생성자를 태우면된다.

결과 

Parent.java
super가 없는 Child.java
super가 있는 Child.java

 

2. 예제 

class Car{
	
    // 매개변수
	String model;
	String color;
	int yyyy:

	Car() {
        this.model = "승용차";
        this.color="검정"
        this.yyyy=2023;
        System.out.println("model : " + model);
	}

	Car(String model, String color, int yyyy){
		this.model = model;
		this.color = color;
		this.yyyy = yyyy:
		System.out.println("model : " + model);
    }
    
    public static void main(String[] args) {
    	int yyyy = 2023;
   	 	Car c = new Car("SUV", "흰색", yyyy++);
    	System.out.print(", year : " + c.yyyy); 
	}

}

// 출력
// model : SUV 
// , year : 2023

 

3. 예제

class A {
	A() { System.out.printf("%d ", 10); } // 디폴트 생성자
    // (3) A의 생성자 호출, 및 10 출력
}

class B extends A {
	B(int a) { System.out.printf("%d ", a); } // C class에서 인자가 있는 생성자를 명시적으로 호출하기 때문에 B() 디폴트생성자 생략이 가능하다.
	// (4) B의 생성자엔 100을 인자로 받은 100 출력
}

class C extends B {

	C(int a) { // (2) 1000인자값을 받아온다. 그리고 생성자는 무조건 최상위 클래스를 호출한다. 
		super(a/10); // 1000/10 = 100을 상위클래스인 B를 호출
        System.out.printf("%d", a); // (5) 1000출력
	}
}



class Test {
	public static void main(String args[]) {
		A b = new C(1000); // (1) A의 인자를 받은 C생성자 b를 생성한다.
	}
}

// 출력값 
10 100 1000

 

예제 4

class A {
	int i;
	public A(int i) { this.i = i; }
    // (3) i=14 인자 받음
	int get() { return i; }
}

class B extends A {

	int i;
    public B(int i) { super(2+i); this.i = i; }
    // (2) i = 7; 대입 , super(명시적 인자) A의 인자값에 14넘김, 
	int get() { return i; }
}


class MAIN {
	public static void main(String args{}) {
	A ab = new B(7); // (1) 상위 Class B 호출 7 인자 넘김
	System.out.println(ab.i + ", " + ab.get());
    // (4) ab.i는 ab의 인자는 A와 가까우니까 14이고 
    //     ab.get() 는 오버라이딩을 했기 때문에 B의 메서드 7이다
    // (5) 14, 7 출력
}

 

댓글