-
자바 생성자(Constructor) 정리Java 2023. 8. 11. 20:33
생성자(Constructor)
- 객체가 생성될 떄, 호출되는 메서드 (메서드는 호출되어야 동작하고 객체가 있어야 한다.)
- 반드시 class의 이름과 같아야한다.
- 객체를 생성하면 반드시 실행되며, 가장 먼저 실행된다.
- 생성자를 정의하지 않으면 컴파일러가 자동으로 기본 생성자를 만든다.
- 생성자를 새로 정의하면 기본 생성자는 만들어지지 않는다.
* 주의 사항 (예시 참고)
error: constructor SubConstructorTest in class SubConstructorTest cannot be applied to given types;
SubConstructorTest() 를 선언하지 않고 사용하면 위와 같은 에러가 난다.예시
class ConstructorTest { ConstructorTest() { System.out.println("# ConstructorTest start"); } void method() { System.out.println("# method"); } } class SubConstructorTest { String sName = ""; int sIdx = 0; SubConstructorTest() { System.out.println("# basic SubConstructorTest"); } SubConstructorTest(String name, int idx) { System.out.println("# SubConstructorTest start"); this.sName = name; this.sIdx = idx; } void printValue() { System.out.println(this.sName+" / "+this.sIdx); } } public class Main { public static void main(String[] args) { ConstructorTest con = new ConstructorTest(); // # ConstructorTest start con.method(); // # method new ConstructorTest(); // # ConstructorTest start SubConstructorTest sCon = new SubConstructorTest("hello world", 100); // # SubConstructorTest start sCon.printValue(); // hello world / 100 SubConstructorTest sub = new SubConstructorTest(); // # basic SubConstructorTest } }'Java' 카테고리의 다른 글
자바 데이터 타입 (0) 2023.08.13 자바 예외 종류 및 Exception 처리 (0) 2023.08.13 Java 특정 값 배열에 포함 여부 (String, int) (0) 2023.08.11 Java 제네릭(Generic) 정리(3)_generic의 extends, super, wildcard (0) 2023.08.11 Java 제네릭(Generic) 정리(2)_static을 이용한 Generic (0) 2023.08.11