我正在做研究,其中我发现了以下内容:
假设我有一个类似下面的类,具有以下构造函数:
public class Triangle implements Shape {
public String type;
public String height;
public Triangle(String type) {
super();
this.type = type;
}
public Triangle(String height) {
super();
this.height = height;
}
public Triangle(String type, String height) {
super();
this.type = type;
this.height = height;
}
}
Run Code Online (Sandbox Code Playgroud)
这给了我一个编译时错误.但是,如果我改变height来自String于int一切工作正常.以下是更改的代码:
public class Triangle implements Shape {
public String type;
public int height;
public Triangle(String type) {
super();
this.type = type;
}
public Triangle(int height) {
super();
this.height = height;
}
public Triangle(String type, int height) {
super();
this.type = type;
this.height = height;
}
}
Run Code Online (Sandbox Code Playgroud)
现在的问题是:假设我想String为height在我的第一种情况; 为什么失败了?请解释.
您不能重载具有相同签名的构造函数
为什么?
虽然解析方法/构造函数来调用JVM需要一些唯一标识方法的东西(返回类型不够),但构造函数/方法的参数必须不一样
看到
你有两个具有相同参数的构造函数.它们都将一个String作为参数.
如果我打电话Triangle tri = new Triangle("blah");没有办法判断"blah"应该是高度还是类型.您可以通过查看来判断,但JVM不能.每个构造函数都必须具有唯一的参数.