一个类使用Java中的两个不同接口实现

时间:2016-11-06 18:21:43

标签: java class interface

我有两个从两个接口实现的类。 这是我的界面:

interface Identifiable {

     int getId();

}

interface Greetable {
    String helloMessage();
    String byeMessage();    
}

这是我的课程:

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;
    }   

}

public class Student implements Greetable, Identifiable {

    private char examScore;

    @Override
    public String helloMessage() {
        return "Hi";
    }

    @Override
    public String byeMessage() {
        return "Whats up";
    }   


}

我从类中获取错误,从接口抽象方法?这是什么意思?

4 个答案:

答案 0 :(得分:2)

非抽象类需要创建在他们正在实现的任何接口中找到的任何方法的具体版本,并且当您的类实现其中一个接口(Greetable接口)的具体版本时,您需要没有实现两个接口的所有方法,这两个类都缺少来自Identifiable接口的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;
    }
}

答案 1 :(得分:1)

您尚未在getId()中实施Identifiable方法。如果您没有实现该方法,则需要将LecturerStudent设为抽象,或者需要在两个类中实现getId()方法。

在您的情况下,我认为您需要创建StudentLecturer的实例。如果是这样,那么就不能将它们视为抽象,因为无法创建抽象类实例。因此,最好在两个类中实现getId()

答案 2 :(得分:1)

您定义实现两个接口,但您只实现了第二个接口的方法。 所以你必须在两个类中实现getId()方法。

答案 3 :(得分:0)

您的StudentLecturer类必须同时实施GreetableIdentifiable interface个方法,否则需要将它们声明为abstract个类即,您遗失getId() Identifiable interface,导致问题,更正了以下代码。

讲师班:

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
    }

您可以查看here

相关问题