[英]Why do I need to add method to a Java interface, to access it in a Junit unit test?
我主要是 C#、.NET 開發人員,習慣於 C# 中的接口和 TDD。 C# 中的接口主要定義了實現時的合約。 Java 中的用法似乎略有不同。 特別是,似乎我遇到的每個項目都實現了用於訪問應用程序的基本接口,就好像任何 Java 應用程序都需要使用接口一樣。 我想我缺少一些基本的理解,所以我真的很感激任何提示我可以閱讀的好入門書。
例如,我有一個看起來像這樣的測試(在我的解決方案中的一個單獨的“測試”文件夾中):
測試。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();
}
Dius保齡球游戲
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();
};
如果它不在接口中,並且您將引用存儲在接口類型的變量中,編譯器如何知道該方法存在?
通常,分配給變量的值可以是BowlingGame
的任何實現。 除非方法在接口上,否則這些類不需要實現該方法。
為避免將方法添加到接口,請將變量類型更改為DiusBowlingGame
,或在setUp
方法中使用局部變量:
DiusBowlingGame bowlingGame = new DiusBowlingGame();
bowlingGame.startGame();
this.bowlingGame = bowlingGame;
據我所知,接口在 C# 和 Java 中的工作方式相同。 唯一的區別是,在 C# 開頭通常用“I”命名接口,在extends
中,類和接口都使用:
運算符,而在implements
上課。 您的代碼不需要接口,它也可以這樣完美地工作:
package com.dius.bowling;
class DiusBowlingGameTest {
private DiusBowlingGame bowlingGame;
@BeforeEach
void setUp() {
this.bowlingGame = new DiusBowlingGame();
this.bowlingGame.startGame();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.