ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 자바(java) 생성자
    Java & Spring 2023. 12. 4. 15:24

    생성자(constructor)란?

    생성자란 인스턴스가 생성될 때 사용되는 '인스턴스 초기화 메서드'입니다.

     

    생성자의 특징

    • 생성자는 반환값이 없지만, 반환타입을 void로 선언하지 않습니다(즉, return이 없다!)
    • 생성자의 이름은 해당클래스의 이름과 같아야 합니다.
    • 클래스에 생성자가 1개도 작성되어있지 않을 경우, 자바가 기본생성자를 자동으로 추가해 줍니다.
    • 기본생성자는 매개변수와 내용이 없는 빈 생성자입니다.
    class Phone {
        String model;	//매개변수
        String color;
        int price;
    
    	//기본생성자 (안보임!)
    }
    
    public class EX {
        public static void main(String[] args) {
            Phone galaxy = new Phone();	//생성자가 없기때문에 파라미터()로 받아오는 값이 없다.
            //모델이 무엇인지?, 색상은 또 무엇인지?, 금액은 얼마인지 알 방법이 없다.
            Phone iphone =new Phone();
            iphone.model = ("아이폰");	//때문에 이런식으로 하나씩 일일히 정의해 주어야 한다.
            iphone.color = ("blue");
            iphone.price = 1500000;
    
            System.out.println("모델 : " + galaxy.model + "  색상 : " + galaxy.color + "  금액 : " + galaxy.price);
            System.out.println("모델 : " + iphone.model + "  색상 : " + iphone.color  + "  금액 : " +iphone.price);
        }

     

    코드량이 적거나 단순할 경우 위와 같은 방법으로도 할 수 있지만, 매번 일일이 정의해 주기가 힘들기 때문에 생성자를 이용하는 것이 좋습니다.

     

    생성자 선언예시)

    class Phone {
        String model;	//매개변수
        String color;
        int price;
    
        public Phone(String model, String color, int price) {
            this.model = model;	
            this.color = color;
            this.price = price;
        }
    }

     

    위 예시처럼 클래스의 생성자는 어떠한 반환값도 명시하지 않습니다.

     

    생성자에서 사용된 this는 생성된 객체 자신을 가리키며 생성자의 매개변수 의 값을 객체의 해당하는 데이터에 넣어주게 됩니다.

    this는 참조변수이며 인스턴스가 바로 자기 자신을 참조하는 데 사용하는 변수입니다.

     

    참조변수 this 예시)

    class Phone {
        String model;	//매개변수
        String color;
        int price;
    
        public Phone(String qwe, String asd, int zxc) {
            this.model = qwe;	
            this.color = asd;
            this.price = zxc;
        }
    }

     

    생성자의 호출

    자바에서는 new 키워드를 사용하여 인스턴스를 생성할 때 자동으로 생성자가 호출합니다.

    class Phone {
        String model;
        String color;
        int price;
    
        public Phone(String model, String color, int price) {
            this.model = model;
            this.color = color;
            this.price = price;
        }
    }
    
    public class constructorEx {
        public static void main(String[] args) {
            Phone galaxy = new Phone("z플립4", "black", 1000000); //파라미터로 model,color,price의 값을 명시해준다.
    
            Phone iphone = new Phone("아이폰14", "spaceGray", 1500000);
    
            System.out.println("모델 : " + galaxy.model + ", " + "색상 : " + galaxy.color + ", " + "금액 : " + galaxy.price);
            System.out.println("모델 : " + iphone.model + ", " + "색상 : " + iphone.color + ", " + "금액 : " + iphone.price);
        }
    }
Designed by Tistory.