- Do it! 자바 프로그래밍 입문 온라인 강의를 수강하며 작성하였습니다.
- Section 1. 자바의 핵심 - 객체지향 프로그래밍
- 9강 "클래스와 객체1(1)"
- 객체지향 프로그래밍과 클래스 > 클래스(class) > 패키지(package)
(접근 제어자) class 클래스명 {
멤버 변수;
메서드;
}
클래스 정의 예시로 아래와 같은 속성을 갖는 클래스를 정의해보겠다.
속성 | 자료형 | 변수 이름 | 설명 |
---|---|---|---|
학번 | int | studentID | 학번은 정수로 나타낼 수 있기 때문에 int형으로 선언 |
이름 | String | studentName | 학생 이름은 문자로 되어있고, 하나의 문자가 아닌 여러 개의 문자로 이루어진 문자열로 표현하므로 String 클래스를 사용 |
학년 | int | grade | 학년은 정수로 나타낼 수 있기 때문에 int형으로 선언 |
사는 곳 | String | address | 문자열을 나타내기 위해 String 클래스를 사용 |
public class Student {
// 멤버 변수를 정의
int studentID;
String studentName;
int grade;
String address;
// 메서드 정의
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();
}
}
위의 예시에서는 코드가 시작되는 main 함수를 class 안에 함께 썼지만, 아래와 같이 다른 클래스에서 Student 클래스를 생성하여 사용할 수 있다.
public class StudentTest {
public static void main(String[] args) {
Student studentHong = new Student(); //클래스 생성
//생성된 클래스의 멤버 변수를 초기화
studentHong.studentID = 20220210;
studentHong.studentName = "홍길동";
studentHong.grade = 2;
studentHong.address = "서울시 서초구 서초동";
//클래스의 메서드 호출
studentHong.showStudentInfo();
}
}
이름을 홍길동으로 바꿔서 showStudentInfo 메서드를 호출했을 때 정상 출력되는 것을 확인할 수 있다.
위 예시는 학교정보시스템 안에서 수업(course)과 학생(Student)로 패키지를 나누고, 각각 데이터베이스와 연동해주는 역할을 하는 소스는 dao(Data Access Object) 패키지에, 화면에 보여지는 소스는 view 패키지에 묶어준 것이다.