Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
Tags
- 정처산기
- 안드로이드
- java
- 파이썬예제
- 정처기운영체제
- 바텀네비게이션
- 파이썬배열
- 업다운게임코드
- 운영체제종류
- 운영체제목적
- 자바예제
- androidstudio
- 파이썬리스트
- 안드로이드스튜디오
- 파이썬
- 자바연산자
- 코딩공부
- 엑티비티
- 데이터베이스
- 스누핑
- 파이썬배열예제
- 파이썬공부
- 정보처리산업기사
- 코딩
- 컴퓨터일반
- 자바
- 정처기
- 백준
- bottomnavigation
- int크기
Archives
- Today
- Total
발전을 위한 기록
[Java] 자바 클래스(Class) 이해하기 본문
728x90
💻 클래스(Class) 정의
- 객체 지향 프로그래밍의 핵심으로, 데이터와 이를 조작하는 메소드를 하나로 묶어 객체를 생성하는 틀입니다.
- 클래스 정의는 class 키워드를 사용하며, 필드(속성)와 메소드(함수)로 구성됩니다.
기본 구문
class ClassName {
// 필드, 메소드, 생성자 등
}
예제
class Student {
String name; // 학생 이름
int age; // 학생 나이
String studentNumber; // 학번
// 생성자
Student(String name, int age, String studentNumber) {
this.name = name;
this.age = age;
this.studentNumber = studentNumber;
}
// 이름, 나이, 학번 출력 메소드
void printStudentInfo() {
System.out.println("Name: " + name + ", Age: " + age + ", Student Number: " + studentNumber);
}
}
public class Main {
public static void main(String[] args) {
// Student 클래스 객체 생성 및 초기화
Student student = new Student("김철수", 20, "S12345678");
// 정보 출력
student.printStudentInfo();
}
}
1. Student 클래스 정의
class Student {
String name; // 학생의 이름
int age; // 학생의 나이
String studentNumber; // 학생의 학번
}
- 'Student' 라는 클래스를 만들어줍니다.
- 클래스는 학생 정보를 담는 하나의 틀과 같습니다.
2.생성자
Student(String name, int age, String studentNumber) {
this.name = name;
this.age = age;
this.studentNumber = studentNumber;
}
- 클래스에서 생성한 객체의 초기 상태를 설정합니다.
- 초기 상태를 설정하는 이유는 객체가 사용되기 전 올바른 데이터와 상태를 가지고 시작할 수 있도록 하기 위함입니다.
3. 출력 메소드
void printStudentInfo() {
System.out.println("Name: " + name + ", Age: " + age + ", Student Number: " + studentNumber);
}
- 학생 정보를 출력하는 printStudentInfo메소드입니다.
- 메소드에 리턴값이 없기 때문에 void로 선언해줍니다.
4. main 클래스
public class Main {
public static void main(String[] args) {
Student student = new Student("김철수", 20, "S12345678");
student.printStudentInfo();
}
}
Student student = new Student("김철수", 20, "S12345678");
- 1번에서 만들었던 Student클래스를 사용해서 틀에 맞는 학생 정보를 넣어줍니다.
student.printStudentInfo();
- 3번에서 만든 메소드를 호출해 학생정보를 출력합니다.
728x90
'프로그래밍 > 자바' 카테고리의 다른 글
[Java] 자바 상속 이해하기 (0) | 2024.02.14 |
---|---|
[Java] 자바 오버로딩(Overloading)과 오버라이딩(Overriding) (0) | 2024.02.06 |
[Java] 자바 메소드(Method)의 이해와 활용 (0) | 2024.02.04 |
[Java] 자바 배열(array) 이해하기 : 선언과 활용 (0) | 2024.02.03 |
[Java] 자바 조건문 (if-else) (0) | 2024.02.01 |