logo

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 

上記の例では、Student クラス コンストラクタ 2 つの異なるコンストラクター (デフォルトとパラメーター化) でオーバーロードされます。

ここで、コンストラクターのオーバーロードの目的を理解する必要があります。場合によっては、クラスのさまざまな値を初期化するために複数のコンストラクターを使用する必要があります。

クラス内でコンストラクターを使用しない場合、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. } } 

コンストラクターのオーバーロードでの this () の使用

ただし、このキーワードをコンストラクター内で使用することができ、これを使用して同じクラスの他のコンストラクターを呼び出すことができます。

コンストラクターのオーバーロードでのこのキーワードの使用を理解するには、次の例を検討してください。

 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