我在同一个项目中有 2 个类(Date
和)。Student
我需要测试Student
该类,但无法在静态方法中调用实例方法。我尝试通过添加Student a = new Student()
under来创建对实例的引用public static void main(String[]args)
,但这需要public Student()
创建一个构造函数。但是,这会导致以下错误:
隐式超级构造函数 Date() 未定义。必须显式调用另一个构造函数
如果我将实例方法更改为静态方法,我就能解决问题。但是想知道是否有其他方法可以在主方法中调用实例方法?
Date
班级:
public class Date {
int day;
int month;
int year;
public Date(int day, int month, int year) {
this.day=day;
this.month=month;
this.year=year;
}
public boolean equals(Date d) {
if(d.day==this.day&&d.month==this.month&&d.year==this.year)
{
return true;
}
else
{
return false;
}
}
public static boolean after(Date d1, Date d2) {
if(d1.day>d2.day&&d1.month>d2.month&&d1.year>d2.year)
{
return true;
}
else
{
return false;
}
}
}
Student
班级:
public class Student extends Date{
public String name;
public boolean gender;
public Student(String name, boolean gender, int day, int month, int year) {
super(day, month, year);
this.name=name;
this.gender=gender;
}
public Student() {
}
public boolean equals(Student s) {
Date d=new Date(s.day,s.month,s.year);
if(s.name==this.name&&s.gender==this.gender&&equals(d)==true)
{
return true;
}
else
{
return false;
}
}
public boolean oldGender(Student[]stds) {
Student old=stds[0];
Date oldDate = new Date(old.day,old.month,old.year);
for(int i=0;i<stds.length;i++)
{
Date d = new Date(stds[i].day,stds[i].month,stds[i].year);
if(after(oldDate,d)==false)
{
old=stds[i];
}
}
return old.gender;
}
public static void main(String[]args) {
Student s1=new Student("Jemima",true,2,3,1994);
Student s2=new Student("Theo",false,30,5,1994);
Student s3=new Student("Joanna",true,2,8,1995);
Student s4=new Student("Jonmo",false,24,8,1995);
Student s5=new Student("Qianhui",true,25,12,1994);
Student s6=new Student("Asaph",false,2,1,1995);
Student[]stds= {s1,s2,s3,s4,s5,s6};
Student a = new Student();
System.out.println(oldGender(stds));
}
}