コンストラクタとは
オブジェクトやフィールドの初期化(変数の宣言と同時に適切な値を格納することで「最初から有効な値が入っている」状態にする)の為に使われる特殊なメソッド。
オブジェクトの生成(インスタンスの生成)とともに自動的に呼び出され、クラスのオブジェクトを生成するタイミング(new クラス名 ())で動作する。
インスタンスの生成と同時に値が代入できるメリットがある。
またインスタンス生成時に自動的に呼び出されるので、最初に変数を定義しておくことが出来、初期化のために別のメソッドを呼ぶ必要がなくなるので、その分コードが簡単になる。
コンストラクタもメソッドの一種なのでオーバーロード(同じ名前のメソッドを複数定義する事)が出来る。
class Student{
:
Student(String n){
:
}
Student(String n, int e, int m){
:
}
}
コンストラクタを定義するには
・名前がクラス名と同じにする。(クラス名と同じなので大文字で名前がスタートする)
・戻り値を持たない(voidも書かない)。
コンストラクタを呼び出す際には
・オブジェクトを作る際に記述する「new クラス名 ()」の()内にコンストラクタへの引数を記述する事でコンストラクタを呼び出す事が出来る。
publec class Student{
:
Student(String n){
:
}
Student(String n, int e, int m){
:
}
}
public static void main(String[] args){
Student stu1 = new Student("菅原");
Student stu2 = new Student("田仲", 75, 100);
:
:
呼び出し側でオブジェクトstu1の引数に("菅原")を渡した場合は定義側ではStudent(String n)のコンストラクタが、オブジェクトstu2の引数に("田仲", 75, 100)を渡した場合はStudent(String n, int e, int m)のコンストラクタが呼び出されて変数に設定される。
クラス内にコンストラクタを記述しない場合はコンパイラが自動的に引数なしのコンストラクタを作成してくれる(コード自体が変わる訳ではない)。これをデフォルトコンストラクタと呼ぶ。
例文
コンストラクタ前
class StuSample3{
public static void main(String[] args){
Student3 stu1 = new Student3();
Student3 stu2 = new Student3();
stu1.setData("菅原");
stu1.setScore(90, 80);
stu1.display();
stu2.setData("田仲", 75, 100);
stu2.display();
}
}
class Student3{
String name;
int engScore;
int mathScore;
void setData(String n){
name = n;
}
void setData(String n, int e, int m){
name = n;
engScore = e;
mathScore = m;
}
void setScore(int e, int m){
engScore = e;
mathScore = m;
}
void display(){
System.out.println(name + "さん");
System.out.println("英語" + engScore + "点・数学" + mathScore + "点");
}
}
コンストラクタ後
class StuSample3{
public static void main(String[] args){
Student3 stu1 = new Student3("菅原");
Student3 stu2 = new Student3("田仲", 75, 100);
stu1.setScore(90, 80);
stu1.display();
stu2.display();
}
}
class Student3{
String name;
int engScore;
int mathScore;
Student3(String n){
name = n;
}
Student3(String n, int e, int m){
name = n;
engScore = e;
mathScore = m;
}
void setScore(int e, int m){
engScore = e;
mathScore = m;
}
void display(){
System.out.println(name + "さん");
System.out.println("英語" + engScore + "点・数学" + mathScore + "点");
}
}
菅原さん
英語90点・数学80点
田仲さん
英語75点・数学100点
コンストラクタ前だとオブジェクトを生成してから値の代入をしているので、変数の中身が設定されていない(データが空っぽ)タイミングが発生してしまう場合がある。
データが空っぽの状態は良くないとされているのでインスタンスの生成と同時に値が代入できるコンストラクタは便利で安全なコードになり、どの値がどのメソッドやオブジェクトに入っているか見やすいコードになる。
参考記事