English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
甲Konstruktion用于在创建时初始化对象。从语法上讲,它类似于一种方法。区别在于,构造函数的名称与其类相同,并且没有返回类型。
无需显式调用构造函数,这些构造函数在实例化时会自动调用。
public class Example { public Example() { System.out.println("Dies ist der Konstruktor der Klasse Beispiel"); } public static void main(String args[]) { Example obj = new Example(); } }
Ausgaberesultat
Dies ist der Konstruktor der Klasse Beispiel
是的,就像方法一样,您可以从构造函数中抛出异常。但是,如果这样做,则需要在调用构造函数的方法处捕获/抛出(处理)异常。如果您不编译,则会生成错误。
在此示例中,我们有一个名为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("Mitarbeitername ist "}+name+"und Alter ist "}+age); } public void display(){ System.out.println("Name: "}+name); System.out.println("Alter: "}+age); } } public class ConstructorExample { public static void main(String args[]) { String filePath = "samplefile.txt"; Employee emp = new Employee("Krishna", 25, filePath); } }
ConstructorExample.java:23error: unreported exception IOException; must be caught or declared to be thrown Employee emp = new Employee("Krishna", 25, filePath); ^ 1 Fehler
Um das Programm ordnungsgemäß auszuführen, umwickeln Sie die Instanziierungszeile in einem try-Block.-im catch-Block oder werfe eine Ausnahme.
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("Mitarbeitername ist "}+name+"und Alter ist "}+age); } public void display(){ System.out.println("Name: "}+name); System.out.println("Alter: "}+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("Datei nicht gefunden"); } emp.display(); } }
Ausgaberesultat
Name: Krishna Alter: 25