先简单写一个类
public class D {
public short dd;
public D(short dd){
this.dd = dd;
}
}
再写一个主方法
public class Test {
public static void main(String[] args) {
// new B().hi();
new D(1);
}
}
这时候发现new D(1);是有报错的。
D(short)’ cannot be applied to '(int)
原因是1默认是int类型的,需要将其强制转换为short
public class Test {
public static void main(String[] args) {
// new B().hi();
new D((short)1);
}
}
这样就没问题了。
另外一个解决报错的办法就是新增int或者long类型的变量和构造器。
public class D {
public short dd;
public byte ddd;
public long dddd;
public int ddddd;
// public D(short dd){
// this.dd = dd;
// }
public D(byte ddd){
this.ddd = ddd;
}
public D(long dddd){
this.dddd = dddd;
}
public D(int ddddd){
this.ddddd = ddddd;
}
}
这样原先的语句就不会报错。
public class Test {
public static void main(String[] args) {
// new B().hi();
// System.out.println( new D((short)1).dd);
// new D((short)1);
new D(1);
}
}
但是和本文讨论侧重点不同。
另一方面,在验证byte是否需要强制转换,给构造器重载时,突然想到另一个需要强制转换的原因。
public class D {
public short dd;
public byte ddd;
public long dddd;
public int ddddd;
public D(short dd){
this.dd = dd;
}
public D(byte ddd){
this.ddd = ddd;
}
// public D(long dddd){
// this.dddd = dddd;
// }
// public D(int ddddd){
// this.ddddd = ddddd;
// }
}
即,当有byte,short这两个构造器存在时,如果不进行强制转换,编译器是没办法判断调用哪个构造函数的。
public class Test {
public static void main(String[] args) {
// new B().hi();
// System.out.println( new D((short)1).dd);
// new D((short)1);
new D(1);
}
}
这段代码的如下报错确实验证如此。
Cannot resolve constructor ‘D(int)’