English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
甲생성객체를 생성할 때 초기화를 위해 사용됩니다. 문법적으로는 메서드와 유사하지만, 생성자의 이름은 클래스와 같으며 반환 타입이 없습니다.
생성자를 명시적으로 호출하지 않아도 됩니다. 이 생성자는 인스턴스화할 때 자동으로 호출됩니다.
public class Example { public Example(){ System.out.println("This is the constructor of the class example"); } public static void main(String args[]) { Example obj = new Example(); } }
출력 결과
This is the constructor of the class example
네, 메서드와 마찬가지로 생성자에서 예외를 던질 수 있습니다. 하지만 이렇게 하면 생성자를 호출하는 메서드에서 예외를 잡아야 합니다./예외를 던지거나 처리합니다. 컴파일하지 않으면 오류가 발생합니다.
아래의 예제에서는 Employee라는 클래스가 있으며, 이 클래스의 생성자가 IOException를 던집니다. 이를 처리하지 않고 클래스를 인스턴스화 했습니다. 따라서 이 프로그램을 컴파일하면 컴파일 시 오류가 발생합니다.
import java.io.File; import java.io.FileWriter; import java.io.IOException; class Employee{ private String name; private int age; File empFile; Employee(String name, int age, String empFile) throws IOException{ this.name = name; this.age = age; this.empFile = new File(empFile); new FileWriter(empFile).write("Employee name is "+name+"and age is "+age); } public void display(){ System.out.println("Name: "+name); System.out.println("Age: "+age); } } public class ConstructorExample { public static void main(String args[]) { String filePath = "samplefile.txt"; Employee emp = new Employee("Krishna", 25, filePath); } }
ConstructorExample.java:23error: 미보고된 예외 IOException; 잡아야 하거나 표시하여 던져야 합니다 Employee emp = new Employee("Krishna", 25, filePath); ^ 1 에러
이 프로그램이 정상적으로 작동하려면, 인스턴스화 줄을 try 블록에 포함시켜 주세요.-catch에서, 또는 예외를 발생시키십시오.
import java.io.File; import java.io.FileWriter; import java.io.IOException; class Employee{ private String name; private int age; File empFile; Employee(String name, int age, String empFile) throws IOException{ this.name = name; this.age = age; this.empFile = new File(empFile); new FileWriter(empFile).write("Employee name is "+name+"and age is "+age); } public void display(){ System.out.println("Name: "+name); System.out.println("Age: "+age); } } public class ConstructorExample { public static void main(String args[]) { String filePath = "samplefile.txt"; Employee emp = null; try { emp = new Employee("Krishna", 25, filePath); }catch(IOException ex) { System.out.println("Specified file not found"); } emp.display(); } }
출력 결과
Name: Krishna Age: 25