생성자는 뭘까?
객체 생성 시 호출되어, 변수들을 초기화 하는 메서드 이다.
바로 예제를보자
package Ex1_constructor;
public class Construtor {
public static void main(String[] args) {
Aclass a = new Aclass();
}
}
class Aclass{
public Aclass() //기본생성자{
System.out.println("Aclass 기본생성자()");
}
}
여기 예제에서 public Aclass가 기본 생성자이다.
Aclass a = new Aclass(); 의 a는 Aclass를 담고있는 변수이다.
예제를 하나더 보자
package Ex1_constructor; public class Construtor { public static void main(String[] args) { new Cellphone(); } } class Cellphone{ String model = "갤럭시"; String color = "빨강색"; int capacity = 60; Cellphone() { System.out.println("model"+model); System.out.println("color"+color); System.out.println("capacity"+capacity); } } |
Cellphone클래스에서 변수를 지정해주었다.
모델명과 색과 용량 3가지.
그 다음 기본 생성자 를 만들어준다음 각각을 출력하였다.
그리고 main에서 생성자를 그대로 실행시켰다.
그러자 기본생성자 안에있는 출력문들이 전부 실행되었다.
여기서 알수있는점.
보통 클래스에서 메서드에 접근할때 객체를 만들었던 기억이있다.
Cellphone cellphone = new Cellphone();
이런식으로 ....
하지만 생성자로부터 접근하려면 new 생성자명 으로 접근한다는것을 알았다.
Cellphone cellphone = new Cellphone(); 작성해주고
cellphone.Cellphone(); 해주면 오류난다....
'(혼) (공) (자)' 카테고리의 다른 글
상속 (0) | 2024.01.12 |
---|---|
Class - 매개변수 생성자 _this (0) | 2024.01.09 |
getter 과 setter 그외(접근제어자) (0) | 2024.01.07 |
class 예제 - 회원정보 입력및 출력 (1) | 2024.01.05 |
class - 예제1(Array) (0) | 2024.01.05 |