コンパイルエラーを無くすだけなら、関数の引数をint型で定義することをすごーくお勧めしますが。
メソッドの引数の型をbyte
型から変更できない場合は、明示的にbyte型にキャストをおこなってください。car.turn((byte)15, 'L');
。
ある数字型からある数字型に変換する時に2パターンあります。
1,int
型からlong
型のように型の取りうる範囲が大きいものに変換する。
これを拡大プリミティブ変換(Widening Primitive Conversion)をいいます。
2,int
型からbyte
型/short
型のように取りうる範囲が小さいものに変換する。
これを縮小プリミティブ変換(Narrowing Primitive Conversion)をいいます。
質問文のコードはcar.turn(15, 'L');
の値:15は他の回答者様も指摘してますが、int
型になります。
そして、public void turn(byte speed,char direction)
とメソッドの引数定義をbyte
型で定義しているため、
int
型→byte
型の縮小プリミティブ変換が行われます。
ここから本題、メソッドの仮パラメータに割り当てるための変換としてJava言語仕様上許可されているのは
5.3. Invocation Contexts
0. 恒等変換
0. 拡大プリミティブ変換
0. 参照型拡大変換
この3つのみです。縮小プリミティブ変換が含まれない理由は
Javaプログラミング言語の設計者は、縮小プリミティブ変換を含めると、以下のコードのようなオーバロードされたメソッドの照合解決過程が複雑になると思ったからとのこと。
Java
1public void turn(byte speed, char direction) { // byte で定義
2 System.out.println("The car is turning " + direction + " by " + speed + " km/h.");
3}
4public void turn(short speed, char direction) { // shortで定義
5 System.out.println("The car is turning " + direction + " by " + speed + " km/h.");
6}
原文はこれです。
5.3. Invocation Contexts
Neither strict nor loose invocation contexts include the implicit narrowing of integer constant expressions which is allowed in assignment contexts. The designers of the Java programming language felt that including these implicit narrowing conversions would add additional complexity to the rules of overload resolution (§15.12.2).
そのためコンパイルエラー(リンク先の英文太文字部分は回答者強調)が発生します。
5.3. Invocation Contexts
If the type of the expression cannot be converted to the type of the parameter by a conversion permitted in a loose invocation context, then a compile-time error occurs.
◇参考
Java言語規定 5. 変換及び昇格
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/06/30 05:19