sivabudh
sivabudh

Reputation: 32635

What is this technique called in Java?

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);
    }
  }
}

Upvotes: 4

Views: 349

Answers (2)

Vincent Ramdhanie
Vincent Ramdhanie

Reputation: 103135

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".

Upvotes: 4

David Sykes
David Sykes

Reputation: 7269

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.

Upvotes: 19

Related Questions