这种技术在 Java 中叫什么?
我是一名 C++ 程序员,当我阅读这个网站时我遇到了下面的例子。这种技术在 Java 中叫什么?它有什么用?
class Application {
...
public void run() {
View v = createView();
v.display();
...
protected View createView() {
return new View();
}
...
}
class ApplicationTest extends TestCase {
MockView mockView = new MockView();
public void testApplication {
Application a = new Application() { <---
protected View createView() { <---
return mockView; <--- whao, what is this?
} <---
}; <---
a.run();
mockView.validate();
}
private class MockView extends View
{
boolean isDisplayed = false;
public void display() {
isDisplayed = true;
}
public void validate() {
assertTrue(isDisplayed);
}
}
}
I'm a C++ programmer, and I was reading this site when I came across the example below. What is this technique called in Java? How is it useful?
class Application {
...
public void run() {
View v = createView();
v.display();
...
protected View createView() {
return new View();
}
...
}
class ApplicationTest extends TestCase {
MockView mockView = new MockView();
public void testApplication {
Application a = new Application() { <---
protected View createView() { <---
return mockView; <--- whao, what is this?
} <---
}; <---
a.run();
mockView.validate();
}
private class MockView extends View
{
boolean isDisplayed = false;
public void display() {
isDisplayed = true;
}
public void validate() {
assertTrue(isDisplayed);
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
那里使用的一般概念是 匿名类
你拥有什么有效的做法是创建一个新的应用程序子类,重写(或实现)子类中的方法。由于子类是未命名的(匿名),因此您无法创建该类的任何其他实例。
您可以使用相同的技术来实现接口或实例化抽象类,只要您在定义中实现所有必要的方法即可。
The general concept being used there is Anonymous Classes
What you have effectively done is to create a new sub-class of Application, overriding (or implementing) a method in sub-class. Since the sub-class is unnamed (anonymous) you cannot create any further instances of that class.
You can use this same technique to implement an interface, or to instantiate an abstract class, as long as you implement all necessary methods in your definition.
正如其他人指出的那样,代码正在创建模拟对象以进行测试。但它也在做一些叫做“匿名内部类”的事情。
As others pointed out the code is creating mock objects for the purpose of testing. But it is also doing something called "Anonymous Inner Class".