본문 바로가기
Programming/Java

Java 생성자 목적,특징, 사용법

by wonduk 2023. 7. 5.
728x90

생성자 목적

  • 생성자는 객체가 생성될때 자동으로 호출되는 함수로 객체를 초기화 할 때 사용합니다.

 

생성자 특징

  • 생성자의 이름은 클래스 이름과 반드시 동일해야 합니다.
  • 생성자 여러 개 작성이 가능합니다(오버로딩)
  • 생성자는 new를 통해 객체를 생성할 때 객체당 한 번 호출합니다
  • 생성자는 리턴 타입을 지정할 수 없습니다.(리턴 타입이 없습니다.)
  • 객체가 생성될 때 반드시 호출 됩니다..
  • 개발자가 생성자를 작성하지 않으면 컴파일러가 자동으로 기본 생성자를 삽입합니다.


기본생성자

  •  매개 변수 없고 아무 작업 없이 단순 리턴하는 생성자
  • 클래스에 생성자가 하나라도 개발자가 작성하면 기본생성자가 자동으로 삽입되지 않음

생성자 사용하기

public class Book {
	String titleString;
	String authorString;
	void show() { System.out.println(titleString + "" + authorString);}
	//기본 생성자
	public Book() {
		this("","");
		System.out.println("생성자 호출됨");
	}
	//매개변수를 가진 생성자
	public Book(String titlesString) {
		this(titlesString,"작자미상");
	}
	//매개변수 2개 가진 생성자
	public Book(String titleString, String authorString) {
		this.titleString = titleString;
		this.authorString = authorString;		
	}
	
	
	public static void main(String[] args) {
    	//Book 객체 생성 및 사용
		Book littlePrince = new Book("어린왕자","생텍쥐페리");
		Book loveStory = new Book("춘향전");
		Book emptyBook = new Book();
		loveStory.show();
		
		Book other = littlePrince;
		other.show();
	}

}

생성자 예제 (2)

public class Circle2 {
	int radius;
	String name;
	//기본 생성자
	public Circle2() {
		radius = 1;
		name = "";
	}
    //매개변수를 가진 생성자
	public Circle2(int r, String n) {
		radius = r;
		name = n;
	}
	public double getArea2(){
		return 3.14*radius*radius;
	}
	
	public static void main(String[] args) {
    	//매개변수를 가진 생성자 사용
		Circle2 pizza = new Circle2(10,"자바피자");
		
		double area = pizza.getArea2();
		System.out.println(pizza.name +"의 면적은" + area);
		
        //기본생성자 사용
		Circle2 donut = new Circle2();
		donut.name = "도넛피자";
		area = donut.getArea2();
		System.out.println(donut.name + "의 면적은" + area);
	}

}

 

 

 

배열을 객체로 생성자 전달하는 예제

public class ArrayParameterEx {
	static void replaceSpace(char a[]) {
		for (int i = 0; i < a.length; i++) {
			if (a[i] == ' ' ) {
				a[i] = ',';
			}
		}
	}
	static void printCharArray(char a[]) {
		for (int i = 0; i < a.length; i++) 
			System.out.print(a[i]);
		
		System.out.println();
		
	}

	public static void main(String[] args) {
		char c[] = {'T','h','i','s',' ','i','s',' ','a',' ','p','e','n','c','i','l','.'};
		printCharArray(c);
		replaceSpace(c);
		printCharArray(c);
	}

}

배열을 객체로 생성자 전달하는 예제(2)

import java.util.Scanner;

import javax.swing.border.TitledBorder;

class Book{
	String title,author;
	protected Book(String title, String author) {
		this.title = title;
		this.author = author;
	}	
}
public class BookArray {
	public static void main(String[] args) {
		Book[] book = new Book[2];
		
		Scanner sc = new Scanner(System.in);
		for (int i = 0; i < book.length; i++) {
			System.out.print("제목>>");
			String title= sc.nextLine();
			System.out.println("저자>>");
			String author = sc.nextLine();
			book[i]= new Book(title, author); 
		}
		for (int i = 0; i < book.length; i++) {
			System.out.print("(" +book[i].title +", " + book[i].author + ")");
		}
	}

}

 

 

728x90