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
- system
- mysql
- Java
- function
- MacOS
- DS
- python
- html
- Algorithm
- web
- react
- Class
- DoM
- control
- php
- Linux
- while
- DATAPATH
- instruction
- MIPS
- for
- DB
- architecture
- XML
- data structure
- javascript
- CSS
- computer
- Pipelining
- github
Archives
- Today
- Total
YYYEJI
[JAVA] Constructor란? 본문
728x90
Constructor란?
Instance variable을 초기화 시켜주는 특별한 method입니다.
Constructor의 특징
- Class와 같은 이름을 가지고 있음
- new 연산자를 통해 객체를 생성할 때 자동으로 가장 먼저 실행됨
- Parameter의 내용을 다르게 해서 1개보다 더 많이 선언될 수 있음(Different signature, overload)
Constructor의 역할
instance variable의 값을 초기화 시키는 역할을 합니다.
Constructor 생성
Constructor은 void, return type이 없고, Parameter의 값이 없는 constructor은 default constructor입니다.
public class p {
private String name;
private int age;
public p() {
name = "";
age = 0;
}
}
instance 변수를 선언해주고 객체가 생성될 때 자동으로 변수를 초기화 시켜주는 constructor도 만들어 주었습니다.
다른 class에서 새로운 p 객체를 생성해 주었습니다.
public class main {
public static void main(String[] args) {
p person_info_1 = new p();
person_info_1.writeOutput();
}
}
constructor의 name은 ""로 age는 0으로 셋팅을 해줬고,
객체 생성 후 객체의 값을 바로 출력했을 때 constructor대로 셋팅되는 것을 확인할 수 있습니다.
◡̈
'Java' 카테고리의 다른 글
[JAVA] Wrapper class란? (0) | 2022.12.27 |
---|---|
[JAVA] Static Method와 Static Variable (0) | 2022.12.27 |
[JAVA] Class Type인 변수 할당하기 (0) | 2022.12.26 |
[JAVA] Setter/Getter 메소드 (0) | 2022.12.26 |
[JAVA] Pass by Value와 Pass by Reference의 차이점 (0) | 2022.12.26 |