2
1

More than 1 year has passed since last update.

Javaのオーバーロード

Posted at

オーバーロードとは

一つのクラス内に同じ名前で引数の型や数が違うメソッドを複数定義する事をオーバーロードという。
同じ名前で定義するだけなのでメソッドの内容(処理)は違う内容にする事が出来る。
オーバーロードするメリットは
・同じデータを設定する為のメソッドなので同じ名前にする事でプログラム自体がわかりやすくなる。
・同じ名前を付けていいので名前をつけるのが楽になる。
・メソッド名が変わらないので呼び出す際に使いやすい。
などがある

例文
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メソッドで出力している。

参考記事

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1