【问题标题】:How to implement a method that ignores some input values? (Java)如何实现忽略某些输入值的方法? (爪哇)
【发布时间】:2018-10-06 13:04:30
【问题描述】:

我是 Java 的初学者。我的第一个任务是创建一个简单的几何对象包——点、线、圆、矩形等。一切正常,但我不确定如何完成其​​他任务:

在这个现有文件中创建一个方法,该方法接受一个对象数组和 返回其面积的总和,但在它们不返回的情况下 有这个参数可用(如类LinePoint), 方法忽略这些对象。

我的猜测是应该使用一个接口(如GeometricObjectObjectWithArea),但我不知道如何使用它。我在想这样的事情:

public interface ObjectWithArea {

   double sumOfAreas(Array) {

   //this is the declaration of the method
  }

}

下面是我如何将接口合并到现有代码中:

class Rectangle implements ObjectWithArea {

   //here are the original parameters and methods of this class

   double sumOfAreas(Array) { 

      //here is the body of the previously declared method

   }
}

但是这个解决方案并没有解决方法应该忽略其他没有实现这个接口的对象的问题。你能帮帮我吗?

【问题讨论】:

    标签: java methods interface


    【解决方案1】:

    您可以使用if (x instanceof ObjectWithArea) 测试您是否应该忽略某个对象,然后使用强制转换((ObjectWithArea)x).getArea() 对您确实需要处理的对象采取行动。

    避免必须这样做的另一种方法(instanceof 有点争议——但不要与你的老师争吵),将getArea 方法用于所有对象并返回0 对于没有区域的人。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-07-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-05
      • 1970-01-01
      相关资源
      最近更新 更多