logo

עומס יתר של קונסטרוקטור ב-Java

ב-Java, אנו יכולים להעמיס בנאים כמו שיטות. ניתן להגדיר את עומס הקונסטרוקטור כרעיון שיש ליותר מבנאי אחד עם פרמטרים שונים כך שכל בנאי יכול לבצע משימה אחרת.

שקול את הדברים הבאים Java תוכנית, שבה השתמשנו בבונים שונים בכיתה.

דוגמא

 public class Student { //instance variables of the class int id; String name; Student(){ System.out.println('this a default constructor'); } Student(int i, String n){ id = i; name = n; } public static void main(String[] args) { //object creation Student s = new Student(); System.out.println('
Default Constructor values: 
'); System.out.println('Student Id : '+s.id + '
Student Name : '+s.name); System.out.println('
Parameterized Constructor values: 
'); Student student = new Student(10, 'David'); System.out.println('Student Id : '+student.id + '
Student Name : '+student.name); } } 

תְפוּקָה:

 this a default constructor Default Constructor values: Student Id : 0 Student Name : null Parameterized Constructor values: Student Id : 10 Student Name : David 

בדוגמה שלמעלה, כיתת הסטודנטים בַּנַאִי עמוס יתר על המידה בשני בנאים שונים, כלומר, ברירת מחדל ופרמטרים.

כאן, עלינו להבין את המטרה של עומס יתר של בנאים. לפעמים, אנחנו צריכים להשתמש במספר בנאים כדי לאתחל את הערכים השונים של המחלקה.

כמו כן, עלינו לשים לב שהמהדר של java מפעיל בנאי ברירת מחדל כאשר איננו משתמשים באף בנאי במחלקה. עם זאת, בנאי ברירת המחדל אינו מופעל אם השתמשנו בבנאי כלשהו במחלקה, בין אם הוא ברירת מחדל או בעל פרמטר. במקרה זה, מהדר Java זורק חריג האומר שהקונסטרוקטור אינו מוגדר.

שקול את הדוגמה הבאה, המכילה את השגיאה מכיוון שלא ניתן ליצור את האובייקט Colleges באמצעות בנאי ברירת המחדל כעת מכיוון שהוא אינו מכיל אחד.

 public class Colleges { String collegeId; Colleges(String collegeId){ this.collegeId = 'IIT ' + collegeId; } public static void main(String[] args) { // TODO Auto-generated method stub Colleges clg = new Colleges(); //this can't create colleges constructor now. } } 

שימוש ב() זה בעומס יתר של בנאים

עם זאת, אנו יכולים להשתמש במילת מפתח זו בתוך הבנאי, אשר ניתן להשתמש בה כדי להפעיל את הבנאי האחר מאותה מחלקה.

שקול את הדוגמה הבאה כדי להבין את השימוש במילת מפתח זו בעומס יתר של בנאים.

 public class Student { //instance variables of the class int id,passoutYear; String name,contactNo,collegeName; Student(String contactNo, String collegeName, int passoutYear){ this.contactNo = contactNo; this.collegeName = collegeName; this.passoutYear = passoutYear; } Student(int id, String name){ this('9899234455', 'IIT Kanpur', 2018); this.id = id; this.name = name; } public static void main(String[] args) { //object creation Student s = new Student(101, 'John'); System.out.println('Printing Student Information: 
'); System.out.println('Name: '+s.name+'
Id: '+s.id+'
Contact No.: '+s.contactNo+'
College Name: '+s.contactNo+'
Passing Year: '+s.passoutYear); } } 

תְפוּקָה:

 Printing Student Information: Name: John Id: 101 Contact No.: 9899234455 College Name: 9899234455 Passing Year: 2018