English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
甲بناءيُستخدم لتحديد التكوين عند إنشاء العنصر. من الناحية النحوية، يشبه طريقة. الفرق هو أن اسم بناء الفئة هو نفس اسم الفئة، وليس لديه نوع عودة.
لا تحتاج إلى استدعاء بناء الفئة بشكل مباشر، هذه الأبناء يتم استدعاؤهم تلقائيًا عند التمثيل.
public class Example { public Example() { System.out.println("هذا هو بناء الفئة مثال"); } public static void main(String args[]) { Example obj = new 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("اسم الموظف هو " + name + " والعمر هو " + age); } public void display(){ System.out.println("الاسم: " + name); System.out.println("العمر: " + age); } } public class ConstructorExample { public static void main(String args[]) { String filePath = "samplefile.txt"; Employee emp = new Employee("Krishna", 25, filePath); } }
ConstructorExample.java:23: خطأ: استثناء لم يتم الإبلاغ عنه 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("اسم الموظف هو " + name + " والعمر هو " + age); } public void display(){ System.out.println("الاسم: " + name); System.out.println("العمر: " + 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("ملف معين غير موجود"); } emp.display(); } }
نتيجة الخروج
الاسم: Krishna العمر: 25