创建 Rectangle 类。此类的数据为 top、left、width、height。
创建尽可能多的 initialize(...) 方法
下面是一些示例:
Requirements:
1. 程序不得从键盘读取数据。
2. Rectangle 类必须包含 int 变量 top、left、width 和 height。
3. 该类必须至少包含一个 initialize 方法。
4. 该类必须至少包含两个 initialize 方法。
5. 该类必须至少包含三个 initialize 方法。
6. 该类必须至少包含四个 initialize 方法
我的代码如下:
public class Rectangle {
public int top;
public int left;
public int width;
public int height;
public void initialize(int top){
this.top = top;
}
public void initialize( int left){
this.left = left;
}
public void initialize(int width){
this.width = width;
}
public void initialize(int height){
this.height = height;
}
public static void main(String[] args) {
}
}
总是错的,这个该咋改,或者问题出在了哪!
如果是方法名报错的话,是因为他们的方法名以及参数都是相同的,所以不构成重载。你可以仿照构造函数,设置他们的方法参数分别为 1 2 3 4个。
public int top;
public int left;
public int width;
public int height;
public void initialize1(int top){
this.top = top;
}
public void initialize(int top,int left){
this.top = top;
this.left = left;
}
public void initialize(int top,int left,int width){
this.top = top;
this.left = left;
this.width = width;
}
public void initialize(int top,int left,int width,int height){
this.top = top;
this.left = left;
this.width = width;
this.height = height;
}
我理解的initialize应该是指多个构造函数(参数不一样),函数名称也不是initialize,而是指初始化的类名,即Rectangle,参考如下:
public class Rectangle {
public int top;
public int left;
public int width;
public int height;
public Rectangle(int top, int left, int width,int height) {
this.top = top;
this.left = left;
this.width = width;
this.height = height;
}
public Rectangle(int top, int left, int width) {
this.top = top;
this.left = left;
this.width = width;
this.height = width;
}
public Rectangle(int top,int left) {
this.top = top;
this.left = left;
this.width = 0;
this.height = 0;
}
public Rectangle(int height) {
this.height = height;
}
public static void main(String[] args) {
}
}
首先函数重载的定义是 参数列表的不同,也就是类型,参数个数。而在你的代码中全部都是public void initialize(int x) 所以编译无法通过