我主要是一名 C#、.NET 开发人员,习惯了 C# 中的接口(interface)和 TDD。 C# 中的接口(interface)主要定义实现时的契约。 Java 中的用法似乎略有不同。特别是,我遇到的每个项目似乎都实现了一个用于访问应用程序的基本接口(interface),就好像任何 Java 应用程序都需要使用接口(interface)一样。我想我缺少一些基本的理解,所以我真的很感激任何关于我可以阅读的好入门书的提示。
例如,我有一个如下所示的测试(在我的解决方案中的单独“测试”文件夹中):
测试.java
package com.dius.bowling;
class DiusBowlingGameTest {
private BowlingGame bowlingGame;
@BeforeEach
void setUp() {
this.bowlingGame = new DiusBowlingGame();
this.bowlingGame.startGame();
}
为了能够访问 this.bowlingGame.startGame();
我需要将该方法添加到界面中。为什么? Java 和 C#/.NET 之间似乎存在我不知道的区别?
界面
package com.dius.bowling;
/**
* Interface for a bowling game.
*/
public interface BowlingGame {
/**
* roll method specifying how many pins have been knocked down
* @param noOfPins no. of pins knocked down
*/
void roll(int noOfPins);
/**
* get player's current score
* @return player's current score
*/
int score();
void startGame();
}
DiusBowlingGame
package com.dius.bowling;
/**
* Scoring system for tenpin bowls
*/
public class DiusBowlingGame implements BowlingGame {
ArrayList<BowlingFrame> gameFrames = new ArrayList<BowlingFrame>();
public void roll (int noOfPins) {
/* Implementation */
}
}
/**
* Activate the 1st frame of the game
*/
public void startGame() {
advanceFrame();
};
最佳答案
如果它不在接口(interface)中,并且您将引用存储在接口(interface)类型的变量中,编译器如何知道该方法存在?
一般来说,分配给变量的值可以是 BowlingGame
的任何实现。除非该方法位于接口(interface)上,否则不需要这些类实现该方法。
要避免将该方法添加到接口(interface)中,请将变量类型更改为 DiusBowlingGame
,或者在 setUp
方法中使用局部变量:
DiusBowlingGame bowlingGame = new DiusBowlingGame();
bowlingGame.startGame();
this.bowlingGame = bowlingGame;
关于java - 为什么我需要向 Java 接口(interface)添加方法,以便在 Junit 单元测试中访问它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58406314/