Search code examples
javaabstractextendinner-classes

Instantiating abstract classes in Java: Why does this work?


Possible Duplicate:
Interview : Can we instantiate abstract class?

I have an abstract class with all its methods defined (i.e. there are no abstract methods contained within it) like the following:

public abstract class MyAbstractClass {
  String s;
  public void setString(String s) {
    this.s = s;
  }
  public String getString() {
    return this.s;
  }
}

There is also a JUnit test class:

public class TestClass {

  MyAbstractClass c;
  @Before
  public void setUp() {
    // What is happening here? And why does this work with an abstract class?
    // Instantiation? Extending the abstract class? Overwriting?
    c = new MyAbstractClass() { };
    // This will not work: (Why?)
    // c = new MyAbstractClass();
  }

  @Test
  public void test_AllMethodsAvailable() {
    // Why can I access the abstract class' methods?
    // Shouldn't they be overwritten? Or did I extend the class?
    c.setString("Test");
    assertEquals("Test", c.getString());
  }
}

I don't quite understand why the assignment to c works in the first case but not in the second, or what is actually happening there (and as a consequence, why accessing the abstract class' methods works in the test).

Can somebody please explain (and possibly point me to a Javadoc, article or book that explains why this works)?

Why can I "instantiate" an abstract class there? (Is that actually what I'm doing?)

Has it to do with inner classes?


Solution

  • You are creating an anonymous inner class with that code. The class you create this way is implicitly extending MyAbstractClass.

    Since your abstract class does not have abstract methods you don't have to provide implementations so this works.

    If you don't know about inner classes you can check the official documentation which is quite nice I think.