Where do constructors go for classes that extend or implement other classes

287 Views Asked by At

I need to create a class called Student that has three private fields: first name, last name, and GPA. Normally, you place a class constructor between the class name and the left bracket, like so: public class Student (firstName, lastName, gpa) {...}

My Student class has to implement the Comparable interface, so my class signature looks like this: public class Student implements Comparable<Student> {...} In this situation, where does my constructor go?

3

There are 3 best solutions below

0
On BEST ANSWER

When you are writing a class, the constructor is a method (or "like a method" depending on your semantics) inside the class. It is not the same as the class declaration.

// This is the class declaration, where the "implements" clause goes
public class Student implements Comparable<Student> {
     ...
     // This is the constructor, which can take whatever parameters you want
     public Student(String firstName, String lastName, float gpa) {
         ...
     }

     // This is the implementation of a method declared by the Comparable<Student> interface
     @Override
     public int compareTo(Student other) {
          ... 
     }
}
0
On

There's no change to the constructor required. What is required is that you implement the methods prescribed by the interface.

That is to say, you could have the same constructor you're using (provided that you provide types for your parameters, which you are not, but you must), but you are required to implement compareTo(Student other) somewhere in your class.

2
On

The constructor would stay the same, regardless of the interface(s) being used on the class.

The interface would only stipulate that you implement 0 or more methods but does not change how the class constructor should be written.