student 클래스에 대해 main 함수에서 2개의 객체를 만들었다고 하자.
Student s1 = new Student("pdy",19990101);
Student s2 = new Student("dlwerma",19920301);
Student 클래스에서 아래와 같은 생성자를 정의했다고 하자.
Student(String name, int birth){
_name = name;
this.birth = birth;
}
이 생성자 영역안에서 매개변수 birth 를 만들었기 때문에, 필드 birth 는 매개변수 birth의 의미가 된다. (인식하는 우선순위에 따라)
따라서 필드를 구분해주기 위해 this 를 붙여준다.
소스 파일 이름과 동일한 클래스만 public 으로 선언가능
ex) A.java 파일에는 클래스 A 만 public 으로 만들수있다.
클래스 B를 추가적으로 만들때 public 을 못만듦
소스 파일당 하나의 클래스를 선언하는 것이 관례임!
(몰론 2개 이상의 클래스도 한 파일에 선언 가능)
하나의 패키지 안에서는 중복으로 같은 클래스를 선언 불가능
ex) package1 패키지에서 A.java 파일과 B.java 파일이 있는데,
두 파일에서 모두 클래스 Student 을 정의할 경우 충돌이 일어난다.
선언한 개수만큼 바이트 코드 파일이 생성
객체 생성 역할 => 생성자를 호출하는 코드
( new로 객체를 생성시 생성자가 반드시 자동으로 호출된다)
생성된 객체는 힙 메모리 영역에 생성
new 연산자는 객체를 생성후, 객체 생성 번지 리턴 => 이로써 참조변수가 힙 영역에 있는 실제 객체를 가리킬 수 있게됨
public class Car{
Car(){ ... }
Car(String model){ ... }
Car(String model, String color){ ... }
Car(String model, String color, int maxSpeed){ ... }
}
this()
public class Book{
String title;
String author;
public Book(){ // 1번 생성자
this(",");
System.out.println("생성자 호출됨");
}
public Book(String title){ // 2번 생성자
this(title, "작가미상"); // 3번 생성자 호출
}
public Book(String title, String author){ // 3번 생성자
this.title = title;
this.author = author;
}
}
pubic static void main(String[] args){
Book littlePrince = new Book("어린왕자", "생텍쥐페리");
Book loveStory = new Book("춘향전");
Book emptyBook = new Book();
loveStory.show();
}
// 실행결과
// 생성자 호출됨
// 춘향전 작자미상