1. 클래스에 대해서 알아 봅시다. (설계도면)
자바에서 클래스(Class)는 객체를 생성하기 위한 템플릿 또는 설계도 역할을 합니다. 클래스는 객체의 상태를 나타내는 필드(변수)와 객체의 행동을 정의하는 메서드(함수)로 구성됩니다. 간단히 말해, 클래스는 데이터와 그 데이터를 조작하는 코드를 묶어 놓은 컨테이너와 같습니다.
package basic.ch05;
//클래스란 객체를 만들기 전 설계도면 입니다.
public class Student {
String name; //학생 이름(문자열)
int grade; //학년 (정수)
String major; //학과 (문자열)
double height;
double weight;
}// end of class
package basic.ch05;
public class Book {
String title;
String author;
int publishYear;
int totalPage;
}//end of class
클래스를 만드는 규칙
- 클래스는 대문자로 시작하는것이 좋음(권장사항)
- 파스칼 케이스(PascalCase)와 카멜 케이스(camelCase) 명명 규칙 사용하기
2. 클래스를 인스턴스화 시켜 봅시다(객체로 만들기)
package basic.ch05;
public class StudentProgram {
//코드의 시작점(메인함수)
public static void main(String[] args) {
int n1 = 1;
double d1 = 5.0;
//대문자 시작은 참조 타입(주소값이 들어간다)
Student student1 = new Student();
Student student2 = new Student();
// . 연산자를 통해서 접근할 수 있다.
student1.name = "홍길동";
//콘솔창에 student1(변수에 연결되어 있는 객체의 이름을 화면에 출력함)
System.out.println(student1.name);
student2.name = "이순신";
System.out.println(student2.name);
System.out.println(student1);
System.out.println(student2);
}//end of main
}//end of class
package basic.ch05;
public class StudentProgram2 {
//코드의 시작점(메인함수)
public static void main(String[] args) {
//우리가 변수에 값을 초기화 하다.
int grade = 10;
String name = "홍길동";
//변수에 선언 - 데이터 타입이 대문자로 시작하고 있다.
Student studentKim;
//변수를 초기화 하다.
studentKim = new Student();
//클래스를 메모리에 올렸다
//클래스를 인스턴스화 했다
Student studentLee = new Student();
}//end of main
}//end of class
package basic.ch05;
public class BookProgram {
//코드의 시작점
public static void main(String[] args) {
//Book 클래스를 인스턴스화 시켜주세요 2개
//참조 타입 변수명은 bookBox1, bookBox2
Book bookBox1 = new Book(); //객체 생성
Book bookBox2 = new Book();
//참조 타입에 변수안에는 실제 값이 들어가는 것이 아니라
//주소값이 담긴다. 레퍼런스 변수 라고도 한다.
System.out.println(bookBox1);
System.out.println(bookBox2);
//Heap 메모리에 생성된 객체에 접근해서
//그 해당 객체의 속성값을 넣어 보자
bookBox1.title = "플러터UI실전";
bookBox1.author = "김근호";
bookBox1.publishYear = 2022;
bookBox1.totalPage = 230;
System.out.println("--------------------------------");
//콘솔창에다가 해당 객체의 속성값(상태값)을 출력해 보자.
System.out.println(bookBox1.title);
System.out.println(bookBox1.author);
System.out.println(bookBox1.publishYear);
System.out.println(bookBox1.totalPage);
//연습문제
//bookBox2 클래스 인스턴스에 접근해서 속성값을 대입하고
//콘솔창 화면에 출력하시오
System.out.println("---------------------------------");
bookBox2.title = "고양이";
bookBox2.author = "치즈고양이";
bookBox2.publishYear = 2024;
bookBox2.totalPage = 4040;
System.out.println(bookBox2.title);
System.out.println(bookBox2.author);
System.out.println(bookBox2.publishYear);
System.out.println(bookBox2.totalPage);
}//end of main
}//end of class
'Java' 카테고리의 다른 글
함수와 메서드 (0) | 2024.04.15 |
---|---|
객체에 값 할당하기 (0) | 2024.04.15 |
OOP(객체지향) 란 (0) | 2024.04.15 |
break, continue 사용 (0) | 2024.04.12 |
while (반복문) (0) | 2024.04.12 |