일단 해보는 코딩/Java

[Java] 생성자(Construct)

eun_zoey2 2022. 8. 7. 16:41
728x90

1. 생성자(Construct) : 객체 생성 시 호출되어, 변수들을 초기화 하는 메서드

'클래스_명 객체_명 = new 클래스_명( )'; 구문 뒤의 클래스_명이 바로 생성자를 호출한다는 의미이다. 

 

    [특징]

      - 클래스와 이름이 같다.

      - 리턴 타입, 반환 값이 없다.

 

 

    [구조]

      - 구현부

                       클래스명 (   ) {   }

      - 호출부

                       클래스명 (   );

 

 

예제 1)

 

package Home22;

public class Constructor2 {
	public static void main(String[] args) {
		new CellPhone();
		//CellPhone myphone = new CellPhone();
		//System.out.println(myphone.model);
	}
}
class CellPhone {
	String model="iphone 12";
	String color = "black";
	int capacity = 256;
	CellPhone(){
		System.out.println("model : "+ model);
		System.out.println("color : " + color);
		System.out.println("capacity : "+ capacity);
	} 
}

 

2. 매개변수 생성자(Construct)

 

    [구조]

      - 구현부

                       클래스명 (자료형 변수명..) {   }

      - 호출부

                       클래스명 (값);

 

예제 2)

 

package Home22;
public class Constructor3 {
	public static void main(String[] args) {
		Bclass b1 = new Bclass("가길동");
		System.out.println(b1.name);
		Bclass b = new Bclass();	//오류, 기본생성자는 생성하지 않고 호출만 하게되면 오류 발생.
		System.out.println(b);
	}
}
class Bclass {
	String name;
	// 생성자 오버로딩 : 여러개의 생성자 중복정의
	Bclass(){} // 기본생성자를 생성하면 위에 뜨는 오류가 정상적으로 실행이 됨
	Bclass(String name){	//매개변수 생성자
		System.out.println("Bclass의 매개변수 생성자()");
		this.name = name;
		
		/* class Bclass {
			String name;
			int x;
			Bclass(String name2){	//매개변수 생성자
				System.out.println("Bclass의 매개변수 생성자()");
				name = name2; */
		        
	}
}

this ? 

현재 객체를 지칭하기 위한 키워드로, 매개변수의 변수 명과 객체내 변수 이름이 같을 경우 this 를 사용해서 구분한다.

 

예제 3)

package Home22;

public class PhoneConstructor {
	public static void main(String[] args) {
		Iphone myphone1=new Iphone();
		Iphone myphone2=new Iphone("iphone SE","white",70);
		System.out.println(myphone1.capacity);
		System.out.println(myphone2.capacity);
	}
}
class Iphone{
	String model;
	String color;
	int capacity;
	Iphone(){}
	Iphone(String model,String color,int capacity){
	this.model=model;
	this.color=color;
	this.capacity=capacity;
}
	void info() {
		System.out.println("model:"+model);
		System.out.println("color:"+color);
		System.out.println("capacity:"+capacity);
	}
}