Java JUnit、接口、类标题
程序员必须为 xyz 程序编写程序。他认识到 Div 和 Add 值都基于相同的底层 Op 数据结构。结果,他编写了以下 JUnit 测试代码。
@Test
public void testDiv() {
Op aValue = new Div(8, 40, “String”);
assertEquals(5, aValue.getVal1());
assertEquals(“String 40 / 8 = 5”, aValue.toString());
}
基于这段代码:为Op编写接口,为Div编写类头。
-- 我的回答是:
public interface IDiv {
String aValue();
String toString();
}
这是正确的吗
public class Div (int, String) {
}
?
A programmer has to write a program for an xyz program. He has recognised that both the Div and Add values are based on the same underlying Op data structure. As a result, he has written the following JUnit test code.
@Test
public void testDiv() {
Op aValue = new Div(8, 40, “String”);
assertEquals(5, aValue.getVal1());
assertEquals(“String 40 / 8 = 5”, aValue.toString());
}
Based on this code: Write an interface for Op and write the class header for Div.
--
My response is:
public interface IDiv {
String aValue();
String toString();
}
and
public class Div (int, String) {
}
is this correct?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我的变体是:
并且
我没有将
toString()
方法添加到Op
接口,因为 Java 中的每个对象都隐式扩展了已经具有的Object
类这个方法。My variant is:
and
I don't add
toString()
method toOp
interface because each object in Java implicitly extendsObject
class which already has this method.我的回答并不完整。我只关注技术要求 - 我的推理仅基于您粘贴的测试代码。根据那里描述的类/对象的语义,更多的结论可以(并且可能应该)被淹没。我们先把它搁置一会儿吧。
您的解决方案似乎并不完全正确(我假设您的意思是
Op
作为您发布的接口名称)。有了这个定义,测试就不会简单地编译。我们知道,无论传递什么Op
实现(此处分配给aValue
变量),它都(至少)有两个方法:getVal1()
toString()
后者是微不足道的,因为 Java 中的每个对象都实现了此方法(
java.lang.Object
所有类的超类保证了这一点)所以
Op
界面应如下所示:可见性修饰符
Op
在这里是一个不太重要的问题。getVal1()
方法的返回类型并不明显。您必须检查它,但可能为了让这一行编译assertEquals(5, aValue.getVal1());
它需要是Integer
,int
或者可能是一些较小的数字类型。我不确定long
或Long
是否适合这里。My answer is not a full one. I focused only on technical requirements - that my reasoning is based only on the test code you've pasted. More conclusions could (and probably should) be drown based on the semantics of the classes/objects described there. Let's put it aside for a while.
Your solution doesn't seem to be fully correct (I assume you've meant
Op
as the interface name you posted). Having this definition, the test wouldn't simply compile. We know that whatever implementation ofOp
is passed (here assigned to theaValue
variable) it has (at least) two methods:getVal1()
toString()
The latter is trivial, because every object in Java has this method implemented (
java.lang.Object
a superclass of all classes guarantees that)So the
Op
interface should look like:The visibility modifier of the
Op
is an issue of low importance here.The return type of the
getVal1()
method is not obvious. You would have to check it, but probably in order for this line to compileassertEquals(5, aValue.getVal1());
it needs to beInteger
,int
or maybe some smaller numeric types. I am not surelong
orLong
would work fit in here.