I've got 2 classes (Date
and Student
) in the same project. I need to test the Student
class but am unable to call an instance method in a static method. I tried to create a reference to the instance by adding a Student a = new Student()
under public static void main(String[]args)
, but this needs a public Student()
constructor to be created. However, this results in the following error:
Implicit super constructor Date() is undefined. Must explicitly invoke another constructor
I am able to solve the problem if I changed the instance method to a static one. But was wondering if there is any other way I can call the instance method in the main method?
Date
class:
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
class:
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));
}
}
When you are extending some class, you are obligated to call 1 of the constructors of that class using super(args)
construct. Constructor of newly created class can be whatever you like.
When extended class have no args constructor, then constructor definition can be ommited in extending class. This may sound like an exception, but in fact it is not. Compiler adds empty constructor on the fly for you.
When you explicitly define empty constructor on the other hand (like you did) you are obligated to call super-class constructor in it.
That is exactly what error says.
public Student() {
//Here you need to call super(int day, int month, int year); as Date(int day, int month, int year)
}
or delcare no args constructor in Date
class