English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
甲CostruzioneUsato per inizializzare l'oggetto durante la creazione. Sintatticamente, è simile a un metodo. La differenza sta nel nome del costruttore che è lo stesso della classe e non ha un tipo di ritorno.
Non è necessario chiamare esplicitamente il costruttore, questi costruttori vengono chiamati automaticamente durante l'istanziazione.
public class Example { public Example() { System.out.println("Questo è il costruttore della classe esempio"); } public static void main(String args[]) { Example obj = new Example(); } }
输出结果
Questo è il costruttore della classe esempio
Sì, come i metodi, è possibile lanciare eccezioni dal costruttore. Tuttavia, se lo fai, è necessario catturare o lanciare (gestire) l'eccezione nel metodo che chiama il costruttore. Se non lo fai, verrà generato un errore.
Nell'esempio seguente, abbiamo una classe chiamata Employee, il cui costruttore lancia IOException, e istanziamo la classe senza gestire l'eccezione. Pertanto, se compili il programma, genererà un errore di compilazione.
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:23: errore: eccezione non segnalata IOException; deve essere catturata o dichiarata come lanciata Employee emp = new Employee("Krishna", 25, filePath); ^ 1 error
Per far si che il programma funzioni correttamente, avvolgi la riga di istanziazione nel try-catch o lancia un'eccezione.
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