有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

类不是Java的抽象类?涉及的界面使用

我正在为家庭作业创建一个程序,该程序使用界面计算火车旅行的成本:

Train Class:

public class Train implements MassTransit {



public void getCapacity() {

    int capacity = 100;



}//end get Capacity


public int getRoundTripCost(int leave, int return_time){
    int cost = 0;
    cost = (return_time - leave) * 100;
    return cost;


} //end getRoundtrip

public static void main(String[] args) {

    Train train = new Train();
    train.getRoundTripCost(20,25);


}//end of main method



}//end train class

以及质量传递法

public interface MassTransit {

public void getCapacity();
public void getRoundTripCost(int leave, int return_time);


}//end of MassTransit interface

当我试图编译Train类时,我得到的错误是“Train.java:6:error:Train不是抽象的,并且不会覆盖MassTransit中的抽象方法getRoundTripCost(int,int)”

Train.java:19:错误:Train中的getRoundTripCost(int,int)无法在MassTransit中实现getRoundTripCost(int,int)

我是一个完全的Java新手,我仍然不熟悉Java接口。我做错了什么


共 (1) 个答案

  1. # 1 楼答案

    public int getRoundTripCost(int leave, int return_time){
        int cost = 0;
        cost = (return_time - leave) * 100;
        return cost;
    
    
    } //end getRoundtrip
    

    上面重写的方法返回类型应该是void而不是int。您的接口定义了返回类型为void的方法

    public void getRoundTripCost(int leave, int return_time);
    

    根据java tutorial

    An instance method in a subclass with the same signature (name, plus the number and the type of its parameters) and return type as an instance method in the superclass overrides the superclass's method.