- Do it! 자바 프로그래밍 입문 온라인 강의를 수강하며 작성하였습니다.
- Section 1. 자바의 핵심 - 객체지향 프로그래밍
- 11강 "클래스와 객체1(3)"
- class & instance > 클래스 생성 > 인스턴스와 힙(Heap) 메모리 > 용어 정리 > 생성자(constructor) > 생성자 오버로드 (constructor overload)
public class Student {
// 멤버 변수를 정의
int studentID;
String studentName;
int grade;
String address;
public String getStudentName() {
return studentName;
}
public void setStudentName(String name) {
studentName = name;
}
// 메서드 정의
public void showStudentInfo() {
System.out.println("학번 : " + studentID);
System.out.println("이름 : " + studentName);
System.out.println("학년 : " + grade);
System.out.println("주소 : " + address);
}
public static void main(String[] args) {
Student studentLee = new Student(); //클래스 생성
//생성된 클래스의 멤버 변수를 초기화
studentLee.studentID = 20220210;
studentLee.studentName = "이순신";
studentLee.grade = 2;
studentLee.address = "서울시 서초구 서초동";
//클래스의 메서드 호출
studentLee.showStudentInfo();
}
}
지난 강의에서 작성했던 코드이다. Student라는 클래스를 호출하기 위한
Student studentLee = new Student(); 코드를 분석해보면 다음과 같다.
용어 | 설명 |
---|---|
객체 | 객체 지향 프로그램의 대상, 생성된 인스턴스 |
클래스 | 객체를 프로그래밍하기 위해 코드로 만든 상태 |
인스턴스 | 클래스가 메모리에 생성된 상태 |
멤버 변수 | 클래스의 속성, 특성 |
메서드 | 멤버 변수를 이용하여 클래스의 기능을 구현 |
참조 변수 | 메모리에 생성된 인스턴스를 가리키는 변수 |
참조 값 | 생성된 인스턴스의 메모리 주소 값 |
// 생성자 기본 문법
<modifiers> <class_name> ([<argument_list>]){
[<statements>]
}
Student class에 작성해보겠다.
public class Student {
// 멤버 변수를 정의
int studentID;
String studentName;
int grade;
String address;
// 생성자(constructor) 정의
public Student(int id, String name) {
studentID = id;
studentName = name;
}
public static void main(String[] args) {
Student studentLee = new Student(); //클래스 생성
//생성된 클래스의 멤버 변수를 초기화
studentLee.studentID = 20220210;
studentLee.studentName = "이순신";
studentLee.grade = 2;
studentLee.address = "서울시 서초구 서초동";
//클래스의 메서드 호출
studentLee.showStudentInfo();
}
}
위와 같이 class 내부에 생성자를 정의할 수 있지만 main()에서 에러가 난다.
그 이유는 생성자를 정의해주었기 때문에 default 생성자를 자동으로 생성해주지 않기 때문이다.
에러를 수정하기 위한 방법은 두 가지가 있다.
1. new Student() 부분을 new Student(20220210, "이순신") 처럼 바꿔준다.
2. class 내부에 default 생성자를 직접 만들어준다. ex) public Student( ) { }
public class Person {
String name;
float height;
float weight;
//default 생성자
public Person() {}
//이름을 매개변수로 입력받는 생성자
public Person(String pname) {
name = pname;
}
//이름, 키, 몸무게를 매개변수로 입력받는 생성자
public Person(String pname, float pheight, float pweight) {
name = pname;
height = pheight;
weight = pweight;
}
}
위와 같이 생성자를 만들어두면 Person클래스를 호출할 때는