[멘토씨리즈] 23강 - 생성자

    SMALL

    1. 기본 생성자

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

     

    (1) 기본 생성자의 구현부와 호출부

    - 구현부 : 클래스명() {}
    - 호출부 : new 클래스명();

     

    (2) 예제 1

    import java.io.*;
    import java.util.*;
    
    public class Main {
      public static void main(String[] args) {
       Aclass a = new Aclass();
      }
    }
    
    class Aclass{
      // 기본생성자 (default 생성자)
      public Aclass(){
        System.out.println("Aclass 기본생성자()");
      }
    }

    - Aclass 호출 시, new Aclass();

     

    (3) 예제 2

    import java.io.*;
    import java.util.*;
    
    public class Main {
      public static void main(String[] args) {
       CellPhone myPhone = new CellPhone();
       System.out.println(myPhone.model);
      }
    }
    
    class CellPhone{
      String model = "Galaxy 8";
      String color = "blue";
      int capacity = 60;
    
      CellPhone() {
        System.out.println("model: " + model);
        System.out.println("color: " + color);
        System.out.println("capacity: " +capacity);
      }
    }

     

     

     

    2. 매개변수 생성자

    (1) 기본 생성자의 구현부와 호출부

    - 구현부: 클래스형(자료형 변수명) {}
    - 호출부: 클래스명(값);

     

    (2) 매개변수 생성자에서 디폴트 생성자

    - 매개변수 생성자 구현 시, 디폴트 생성자가 없으면 디폴트 생성자 호출 불가!

    => 디폴트 생성자를 따로 만들어 줘야함.

    - 기본 생성자에서는 디폴트 생성자 자동 생성

     

    (3) this 키워드

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

     

    (4) 생성자 오버로딩

    - 여러 개의 생성자 중복 정의

    - 예제 1의 경우, 디폴트 생성자와 매개변수 생성자의 클래스 명이 동일 -> 즉, 오버로딩됨.

     

    (5) 예제 1

    import java.io.*;
    import java.util.*;
    
    public class Main {
      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; 
      }
    }

     

    (6) 예제 2

    import java.io.*;
    import java.util.*;
    
    public class Main {
      public static void main(String[] args) {
        Iphone myPhone = new Iphone();
        Iphone myPhone2 = new Iphone("Iphone 14", "yellow", 128);
    
        myPhone.info();
        myPhone2.info();
    
        System.out.println(myPhone.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);
      }
    }
    728x90

    댓글