객체지향언어는 현실세계처럼 객체간의 협력 관계를 프로그래밍하는 언어입니다.
객체는 프로그램에서 구현하고자하는 대상이며 클래스는 객체를 위한 설계도로 볼 수 있습니다.
객체는 어떻게 생성할까요??
Example ex = new Example();
위 문장은 Example 클래스의 객체(인스턴스)를 생성하는 코드이며 아래처럼 해석할 수 있습니다.
(Oracle에서 제공하는 Java Documentation 참고)
1. Declaration: The code set in bold are all variable declarations that associate a variable name with an object type.
2. Instantiation: The new keyword is a Java operator that creates the object.
3. Initialization: The new operator is followed by a call to a constructor, which initializes the new object.
1. 선언: 객체의 타입과 변수의 이름을 나타내는 참조변수 선언부
2. 객체생성: 객체를 생성하는 'new' 연산자
3. 초기화: 새로운 객체를 초기화하는 생성자
참조변수 선언
Student studentJack;
만약 참조변수를 위처럼 선언한다면, 객체가 생성되고 위 변수에 저장되기 전까지 studentJack은 값이 없기 때문에 compile error가 발생합니다.
객체 생성
- new 연산자를 통해 객체를 생성합니다.
- 이때, new연산자는 객체를 위한 (heap)메모리를 할당하고 메모리주소(해시코드)를 반환받습니다.
- 객체의 생성자를 호출하며, 생성자는 객체생성을 위한 클래스의 이름을 제공합니다.
위 과정에서 new연산자가 제공하는 reference(메모리주소)는 참조변수에 저장됩니다.
([참고] '클래스를 인스턴스화하다, 또는 인스턴스를 생성하다'는 '객체를 생성하다'와 같은 의미입니다.)
초기화
- 생성자를 통해 새롭게 생성된 객체를 초기화합니다.
- 즉, 생성자의 형태에 따라 객체의 속성의 초기화가 이루어집니다.
* 생성자(constructor)는 클래스와 이름이 같으며 return을 필요로하지 않습니다.
예) 아래에 클래스 Rectangle에는 생성자가 4개 존재합니다.
public class Rectangle {
public int width = 0;
public int height = 0;
public Point origin;
// four constructors
public Rectangle() {
origin = new Point(0, 0);
}
public Rectangle(Point p) {
origin = p;
}
public Rectangle(int w, int h) {
origin = new Point(0, 0);
width = w;
height = h;
}
public Rectangle(Point p, int w, int h) {
origin = p;
width = w;
height = h;
}
객체를 생성하여 참조변수 rectOne에 저장합니다.
Rectangle rectOne = new Rectangle(100, 200);
이때 생성된 객체의 필드 width와 height은 100, 200으로 초기화됩니다.
* 매개변수의 숫자와 자료형에따라 자바컴파일러는 생성자들을 구별합니다. (메소드도 마찬가지)
결론
ClassName refVariable = new ClassName();
위와 같은 객체생성식을 통해
new연산자를 가지고 객체를 생성하여 객체에 대한 접근정보를 참조변수에 저장합니다.
+따라서, 참조변수를 통해 객체의 속성(필드), 메소드에 접근할 수 있습니다.
<Study more>
1. 객체를 생성하고 얻은 참조정보(reference)는 필요에 따라 참조변수에 저장되지 않고 직접 사용될 수
있습니다.
int recHeightA = new Rectangle().height;
- 새로운 객체를 만들어 객체의 height필드값을 recHeightA에 저장
-참고-
docs.oracle.com/javase/tutorial/java/javaOO/objectcreation.html
Creating Objects (The Java™ Tutorials > Learning the Java Language > Classes and Objects)
The Java Tutorials have been written for JDK 8. Examples and practices described in this page don't take advantage of improvements introduced in later releases and might use technology no longer available. See Java Language Changes for a summary of updated
docs.oracle.com
www.geeksforgeeks.org/new-operator-java/
new operator in Java - GeeksforGeeks
A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.
www.geeksforgeeks.org
'Java' 카테고리의 다른 글
Anonymous Class (익명 클래스)란? (+ GUI에서의 활용) (0) | 2021.05.22 |
---|---|
char - int 형변환 살펴보기 (0) | 2021.05.18 |
[OOP] 클래스, 객체, 인스턴스 in Java (0) | 2021.05.03 |
지역변수(local variable) (0) | 2021.04.28 |
상수와 리터럴 (0) | 2021.04.27 |