以包含接口(interface)对象的数组作为参数的 Java 方法

标签 java interface

所以我有一个由名为 Vehicle 的类实现的接口(interface),该类接受 double 值作为参数:

public class Vehicle implements Efficiency
{
  //instance variable
  private double efficiency;

  public Vehicle(double x)
  {
  //parameter initializes the instance variable 
  x = efficiency; 
}

这是界面:

public interface Efficiency 
{
  double getEfficiency(); 
}

我需要创建一个名为 getFirstBelowT() 的方法,该方法接受 Efficiency 数组和 double 作为参数。该方法应该返回一个 Efficiency 对象,该对象是数组中小于参数中的 double 值的第一个对象。如何将效率数组中的元素与 double 值进行比较?这是我到目前为止所拥有的:

//a method that returns an Efficiency object that is the first
//object in the array with a efficiency below the double parameter

public static Efficiency getFirstBelowT(Efficiency[] x, double y)
{ 
    //loop through each value in the array
    for(Efficiency z: x)
    {
        //if the value at the index is less than the double
        if(z < y)
        {   //returns the first value that is less than y and stops looping
            // through the array.
            return z; 
            break; 
        }
    }
    //returns null if none of the element values are less than the double                
    return null;
}

最佳答案

你基本上就在那里:

  1. 您需要在条件中调用 getEfficiency 方法:

    if(z.getEfficiency() < y)
    
  2. 去掉return之后的break:这是无法访问的代码。

关于以包含接口(interface)对象的数组作为参数的 Java 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33336450/

相关文章:

java - Spring 启动: Configuration Scan missing classes due to "weird" setup

java - 我的合法域名不是合法的 Java 包名

java - DWR - Jetty 9 中的 splinter 反射异常

java - 如何在Java中实现扩展另一个通用接口(interface)的通用接口(interface)?

c++ - 虚拟类多重继承

Java "extending"一个对象

angular - Typescript 中接口(interface)和类的区别

java - "Passing arguments"通过 ThreadLocal 好吗?

java - JAVA和MYSQL如何删除一条记录(字符串)

Java 泛型嵌套类型参数