티스토리 뷰

2. 생성자

1. 생성자 개요

  • Constructor는 클래스로부터 객체를 생성할 때 호출되며, 객체의 멤버 변수를 초기화하는 메서드다.
  • 클래스와 같은 이름을 가진 메서드다.
  • 일반 메서드와 달리 반환형 (Return Type)이 없으며 void도 허용되지 않는다.
  • 생성자는 이름은 같지만 매개변수를 달리하여 여러 개를 중복정의 (Overloading)할 수 있다.
  • 생성자는 객체를 생성할 때 new 생성자() 구문으로 호출된다.
  • 명시적으로 작성하지 않을 경우 기본 생성자가 제공된다.

 

기본 생성자 (Default Constructor)

  • 클래스에 생성자가 하나도 정의되지 않은 경우, 컴파일러에 의해 자동으로 생성되는 생성자

  • 매개변수가 없는 생성자

class Employee {
    // 생성자를 가지고 있지 않은 클래스 => 기본 생성자 자동 추가
    String name;
    int number;
    int age;
    String title;
    String dept;
    String grade;
}

public class DefaultConstructorTest {
    public static void main(String[] args) {
        Employee kim  = new Employee(); // 기본 생성자로 초기화됨
        System.out.println("이름 : " + kim.name);
        System.out.println("사번 : " + kim.number);
        System.out.println("나이 : " + kim.age);
        System.out.println("직함 : " + kim.title);
        System.out.println("근무 부서 : " + kim.dept);
        System.out.println("등급 : " + kim.grade);

//        이름 : null
//        사번 : 0
//        나이 : 0
//        직함 : null
//        근무 부서 : null
//        등급 : null
    }
}

 

Constructor 생성

  • 생성자 자동 생성 : Alt + Shift + S => Generate Constructor using Fields
class Employee {
    String name;
    int number;
    int age;
    String title;
    String dept;
    String grade;

    // 사원의 이름과 나이를 초기화하는 생성자
    // public Employee(String n, int a) {
    //    name = n;
    //    age = a;
    // }

    // Alt + Shift + S => Generate Constructor using Fields
    public Employee(String name, int number, int age, String title, String dept, String grade) {
        super();
        this.name = name;
        this.number = number;
        this.age = age;
        this.title = title;
        this.dept = dept;
        this.grade = grade;
    }
}

public class EmployeeTest {
    public static void main(String[] args) {
        Employee sung = new Employee("성나정", 25); // 매개변수 두 개로 생성자 호출, 객체 생성, 초기화
        System.out.print(sung.name + " 사원의 나이 : " + sung.age);
//        성나정 사원의 나이 : 25
    }
}

 

2. this의 의미와 사용법

  • 생성자나 메서드의 매개변수 이름이 객체 변수의 이름과 같다면, 객체 변수 이름 앞에 this를 사용해서 구별한다.
  • 일반 메소드에서도 this 사용
class Employee {
    String name;
    int age;

    public void setName(String name) {
        this.name = name;
    }
    public void setAge(int age) {
        this.age = age;
    }
}

 

출처 - swexpertacademy.com/

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
글 보관함