Search code examples
javaclassconstructorcomparable

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


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?


Solution

  • 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) {
              ... 
         }
    }