기술(Tech, IT)/자바(Java)

[Java] 생성자(Constructor)

Daniel803 2022. 9. 14. 13:13

Oracle Java Documentation에 따르면 생성자(Constructor)의 정의는 아래와 같다.

: A constructor is used in the creation of an object that is an instance of a class. Typically it performs operations required to initialize the class before methods are invoked or fields are accessed. Constructors are never inherited.

: 생성자는 한 클래스의 인스턴스인 객체를 생성할 때 사용된다. 일반적으로 생성자는 메소드가 호출되거나 *필드(지역 변수, 인스턴스 변수, 클래스 변수)가 접근되기 전에 클래스를 초기화 하기 위해 사용된다. 생성자는 절대 상속되지 않는다.

 

1. 생성자 선언

 아래와 같은 문법으로 생성자를 선언한다. 설계에 따라 public, protected, private으로 선언 가능하며 생략도 가능하다. 아무 생성자도 선언되지 않았다면 묵시적으로 기본 생성자가 생성된다. (private 생성자는 Singleton과 같은 경우에 사용된다.)

 

(public, protected, private) 클래스(매개변수) {

    변수 초기화

}

일반적인 생성자 선언 예시:

public Book(String title, String author, float price) {
    this.title = title;
    this.author = author;
    this.price = price;
}

기본 생성자 예시:

public Book() { }

2. 생성자 사용

 다음과 같이 생성자를 사용할 수 있다.

public class BookTest {
    private Book book;
    public static void main(String[] args) {
        book = new Book("Java", "Daniel", 100);
    }
}

3. 생성자 오버로딩(Overloading)

 의도와 주어지는 데이터에 따라 생성자의 변수를 다르게 초기화 해야되는 경우를 위해 매개변수만 다른 생성자 오버로딩을 할 수 있다.

public Book() { }

public Book(String title) {
    this.title = title;
}

public Book(String title, String author, float price) {
    this.title = title;
    this.author = author;
    this.price = price;
}

 

* 필드(Field)

class class_name {
    static data_type variable_name; // 클래스 변수
    data_type variable_name; // 인스턴스 변수    
    data_type method_name() {
        data_type variable_name; // 지역 변수
    }
}

 

출처:

1. https://docs.oracle.com/javase/tutorial/reflect/member/ctor.html

 

Constructors (The Java™ Tutorials > The Reflection API > Members)

The Java Tutorials have been written for JDK 8. Examples and practices described in this page don't take advantage of improvements introduced in later releases and might use technology no longer available. See Java Language Changes for a summary of updated

docs.oracle.com

2. https://dev01.tistory.com/68

'기술(Tech, IT) > 자바(Java)' 카테고리의 다른 글

[Java] Queue(큐) 선언 및 사용  (0) 2022.09.27
[Java] 전역 변수(Global variable)  (0) 2022.09.18
[Java] JAR(Java Archive)  (0) 2021.09.18
[Java] instanceof  (0) 2021.08.23
[Java] String, StringBuilder, StringBuffer  (0) 2021.07.06