一个类从Java中的两个不同接口实现
我有两个类,它们通过两个接口实现。 以下是我的界面:一个类从Java中的两个不同接口实现,java,class,interface,Java,Class,Interface,我有两个类,它们通过两个接口实现。 以下是我的界面: interface Identifiable { int getId(); } 以下是我的课程: public class Lecturer implements Greetable, Identifiable { private int employeeId; private String name; private String title; @Override public
interface Identifiable {
int getId();
}
以下是我的课程:
public class Lecturer implements Greetable, Identifiable {
private int employeeId;
private String name;
private String title;
@Override
public String helloMessage() {
return name;
}
@Override
public String byeMessage() {
return title;
}
}
我从类中得到错误,它必须从接口中抽象方法?这意味着什么?非抽象类需要创建在它们所实现的任何接口中找到的任何方法的具体版本,而当您的类实现其中一个接口(Greetable接口)的具体版本时,您并没有实现这两个接口的所有方法,这里是
public int getId()
两个类都缺少可识别接口中的方法
解决方案:为这两个类提供一个int-id字段以及返回该字段所持有值的getId()
方法
e、 g.对于学生
public class Student implements Greetable, Identifiable {
private char examScore;
private int id; // **** your classes will need this field ****
// need to set the ID somehow, either with a setter or a constructor
public Student(int id) {
this.id = id;
}
@Override
public String helloMessage() {
return "Hi";
}
@Override
public String byeMessage() {
return "Whats up";
}
@Override // **************** add this method to return the value held by id ******
public int getId() {
return this.id;
}
}
您尚未在
identification
中实现getId()
方法。如果没有实现该方法,则需要将讲师
和学生
抽象化,或者需要在这两个类中实现getId()
方法
在您的案例中,我认为您需要创建
学生
和讲师
的实例。如果是这样,则不能将它们作为抽象类,因为无法创建抽象类实例。因此,最好在这两个类中实现getId()
。您的学生
和讲师
类必须同时实现Greetable
,可识别
接口方法,否则它们需要声明为抽象
类,即您缺少getId()
来自引起问题的可识别的
接口
,更正了下面的代码
讲师班:
public class Lecturer implements Greetable, Identifiable {
int getId() {
return employeeId;
}
//all other existing methods
}
public class Student implements Greetable, Identifiable {
int getId() {
return studentId;
}
//all other existing methods
}
学生班:
public class Lecturer implements Greetable, Identifiable {
int getId() {
return employeeId;
}
//all other existing methods
}
public class Student implements Greetable, Identifiable {
int getId() {
return studentId;
}
//all other existing methods
}
您可以查看您定义的实现两个接口的方法,但是您只实现了第二个接口的方法。 因此,您必须在这两个类中实现getId()方法