构造函数在哪里用于扩展或实现其他类的类

时间:2014-11-20 17:07:04

标签: java class constructor comparable

我需要创建一个名为Student的类,它有三个私有字段:名字,姓氏和GPA。通常,在类名和左括号之间放置一个类构造函数,如下所示:public class Student (firstName, lastName, gpa) {...}

我的Student类必须实现Comparable接口,所以我的类签名如下所示:public class Student implements Comparable<Student> {...}在这种情况下,我的构造函数在哪里?

3 个答案:

答案 0 :(得分:2)

所需的构造函数没有变化。 所需要的是您实现接口规定的方法。

也就是说,你可以拥有你正在使用的相同构造函数(前提是你提供的参数类型,你不是,但你必须),但你是需要在班级的某个地方实施compareTo(Student other)

答案 1 :(得分:0)

无论在课程中使用interface(s),构造函数都保持不变。

interface只会规定您实现0个或更多方法,但不会改变应该如何编写类构造函数。

答案 2 :(得分:0)

当你编写一个类时,构造函数是一个方法(或者#34;就像一个方法&#34;取决于你的语义)在类中。它与类声明不同。

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