java 기초 공부 내용 정리(생성자)

홍준성·2022년 6월 2일
0

java 기초 공부

목록 보기
18/39

생성자란

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

  • 클래스와 이름이 같다.
  • 리턴 타입, 반환값이 없다.

기본 생성자

[구현부]
클래스명(){}
Aclass(){
	x=100;
}

[호출부]
클래스명();
new Aclass();
	public static void main(String[] args) {
		
		Aclass a = new Aclass();
		
		
	}
}

class Aclass{
	//기본 생성자(default 생성자)
	public Aclass() {
		System.out.println("Aclass 기본생성자()");
	}
}
public static void main(String[] args) {
		
		CellPhone myPhone = new CellPhone();
		System.out.println(myPhone.model);
		
		
	}
}

class CellPhone{
	String model="Galaxy 8";
	String color="red";
	int capacity=60;
	CellPhone(){
		System.out.println("model:"+model);
		System.out.println("color:"+color);
		System.out.println("capacity:"+capacity);
	}
	
}

매개변수 생성자

[구현부]
클래스명(자료형 변수명..){}
Bclass(int a){
	x=a;
    System.out.println("Bclass(): 매개변수 생성자, x:"+a
}


[호출부]
클래스명(값);
new Bclass(10);

this란?

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

	public static void main(String[] args) {
		Bclass b = new Bclass("가길동");
		System.out.println(b.name);
	}
}

class Bclass{
	String name;
	Bclass(String name){//매개변수 생성자
		System.out.println("Bclass의 매개변수 생성장()");
		this.name= name2; // String name과 Bclass(String name)에서 변수(name)이 같기 때문에 this.name이 가능하다
	}
}
profile
준성이의 개발자 공부 velog

0개의 댓글