我试图在Java中实现构造函数重载。我认为一切都很完美,但它显示了以下错误:
Main.java:28:错误:类Tryme中的构造函数Tryme不能为
适用于给定的类型;
Tryme s=new Tryme(1,1,2015);
^ required: no arguments found: int,int,int reason: actual and formal argument lists differ in length 1 error .
这是我的代码:
import java.util.*;
class Try1 {
int day,month,year;``
public void Try1() {
day = 1;
month = 1;
year = 2015;
}
public void Try1(int d,int m,int y) {
day = d;
month = m;
year = y;
}
public void seter() {
System.out.println(day+"/"+month+"/"+year);
}
}
class MDate {
public static void main(String []str) {
Try1 t = new Try1();
t.seter();
Try1 s=new Try1(1,1,2015);
s.seter();
}
}
最佳答案
构造函数未使用任何显式的返回类型,但您使用void作为返回类型。您必须从构造函数中删除void。
使用如下构造函数:
public Try1() {
day = 1;
month = 1;
year = 2015;
}
public Try1(int d, int m, int y) {
day = d;
month = m;
year = y;
}