オーバーロードとは
一つのクラス内に同じ名前で引数の型や数が違うメソッドを複数定義する事をオーバーロードという。
同じ名前で定義するだけなのでメソッドの内容(処理)は違う内容にする事が出来る。
オーバーロードするメリットは
・同じデータを設定する為のメソッドなので同じ名前にする事でプログラム自体がわかりやすくなる。
・同じ名前を付けていいので名前をつけるのが楽になる。
・メソッド名が変わらないので呼び出す際に使いやすい。
などがある
class Student{
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;
}
}
上記のStudentクラスではsetDataメソッドを二つ定義(オーバーロード)している。
片方のsetDataメソッドではString型の引数一つを、もう片方ではString型の引数一つとint型の引数二つ持ったsetDataメソッドになっている。
呼び出す側でどちらのsetDataメソッドを呼び出すかは名前と引数の型、数の組み合わせで決めている。
public static void main(String[] args){
Student stu = new Student();
stu.setData("菅原");
stu.setData("菅原", 75, 100);
:
}
}
呼び出す側で名前と引数の組み合わせが合うものがなけれがコンパイルエラーになる。
戻り値の型は違っていても呼び出せる
例文
class StuSample2{
public static void main(String[] args){
Student2 stu1 = new Student2();
Student2 stu2 = new Student2();
stu1.setData("菅原");
stu1.setScore(90, 80);
stu1.display();
stu2.setData("田仲", 75, 100);
stu2.display();
}
}
class Student2{
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 + "点");
}
}
菅原さん
英語90点・数学80点
田仲さん
英語75点・数学100点
Student2クラス内にはString型を一つ受け取って変数に代入する6行目のsetDataメソッドとString型一つとint型二つを受け取って代入する9行目のsetDataメソッドがオーバーロードされている。
StuSample2クラスではStudent2クラスから二つのオブジェクトを生成している。
StuSample2クラス内の6〜9行目でStudent2クラス内の6行目のsetDataメソッドとsetScoreメソッドに値を格納してdisplayメソッドで出力している。
StuSample2クラス内の10~11行目でStudent2クラス内の9行目のsetDataメソッドにそれぞれ("田仲", 75, 100);という値を格納しdisplayメソッドで出力している。
参考記事