0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Java入門 オーバーロード

Posted at

Java入門
オーバーロード

プログラミングしていくうちに、同じような処理を行うメソッドを複数作る必要が出てくることがあります。しかし、メソッドは同じ名前をつける事ができません。
しかし、例外的に同じ名前を複数定義する方法があり、それをオーバーロード(多重定義)といいます。

sample.java
public class Sample {
	// int型のaddメソッド
	public static int add(int x, int y) {
		return x + y;
	}
	// double型のaddメソッド
	public static double add(double x, double y) {
		return x + y;
	}
	// String型のaddメソッド
	public static String add(String x, String y) {
		return x + y;
	}
	public static void main(String[] args) {
		// int型のメソッドの呼び出し
		System.out.println(add(10, 20));
		// double型のメソッドの呼び出し
		System.out.println(add(5.5, 2.2));
		// String型のメソッドの呼び出し
		System.out.println(add("世界一", "かわいいよ!"));
	}
}

実行結果

sample
30
7.7
世界一かわいいよ!

オーバーロードは仮引数の型や個数が異なれば、同じ名前のメソッドを複数定義する事が可能です。

0
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?