Back-End/Java
[Java] 객체 지향 언어(OPP) - 객체, 클래스
nanee_
2021. 8. 23. 16:18
728x90
반응형
SMALL
객체 (Object)
: 상태와 행위를 뽑아낼 수 있는 현실 세계에 존재하는 모든 것
instance 라고 부른다.
클래스 (Class)
객체를 정의하는 설계도
객체의 상태와 행위(method)를 클래스 안에서 구현해 낼 수 있다.
클래스 안에서,
객체의 상태 -> 변수로, 객체의 행위(기능) -> 메서드로 표현한다.
- 설계해보기
객체 : '학생'
public class Student{
// 객체의 상태
int height; // 키
int weight; // 몸무게
String name; // 이름
}
Student 클래스 안에서 변수를 선언했다.
이 변수는 '학생' 객체의 상태이다.
height(키), weight(몸무게), name(이름) 을 멤버 변수라고 한다.
public class StudentMain{
public static void main(String[] args){
// 참조타입 선언과 동시에 초기화
Student student1 = new Student();
student1.name = "나재민";
student1.height = 178;
student1.weight = 63.8;
System.out.println(student1); //ch01.Student@7de26db8 주소값
System.out.println(student1.name); // 나재민
System.out.println(student1.height); // 178
System.out.println(student1.weight); // 63.8
}
}
StudentMain 클래스에서는 Student 클래스에서 선언한 변수에 접근해 사용하려고 한다.
참조타입 변수인 student1을 선언하고, new 키워드를 사용해서 초기화를 해준다.
선언한 변수인 student1에 점(.)을 찍어서 멤버 변수에 접근하고,
대입연산자로 초기화를 해줄 수 있다.
student1을 출력해보면 주소값이 나오게 된다.
이는 Heap메모리에 저장되어 있는 공간의 주소값을 Stack 메모리에서 가지고 있기 때문에
student1은 점(.)으로 멤버 변수에 접근하기 전이니 그 주소값을 가지고 있는 것이다.
728x90
반응형
LIST