0

I am a junior developer and I am familiar with the theory behind java abstract classes and how they can have constructors to force subclasses to set certain constructor parameters, and how abstract classes themselves cannot be instantiated. However, when looking at some refactored code in my company's test framework I am slightly puzzled.

This abstract class

public abstract class WaitForTestOutcomeThenAssert {

   private long maxWait;

   public WaitForTestOutcomeThenAssert(long maxWait) {
      this.maxWait = maxWait;
   }

   public void waitForConditionThenAssert() {
    ...
    ...
   }

   protected abstract boolean checkCondition();
}

gets referenced in this class:

public class DbWrapper extends AbstractDB {

    @Override
    public void assertColumnValueNotNull(final String schema, final String table, final String columnName, final String whereClause) {

        new WaitForTestOutcomeThenAssert(this.assertionTemporalTolerance) {

             @Override
             public boolean checkCondition() {
                 return getColumnValue(schema, table, columnName, whereClause) != null;
             }
       }.waitForConditionThenAssert();
   }
}

Since we can't instantiate an abstract class, can someone please explain to me exactly what happens and what gets created when we use new keyword in front of an abstract class constructor?

user283188
  • 287
  • 3
  • 11
  • 19
  • That is an [anonymous class](http://www.docstore.mik.ua/orelly/java-ent/jnut/ch03_12.htm). Basically a class declared inline without a name. – clcto Sep 25 '14 at 15:31
  • possible duplicate of [How are Anonymous (inner) classes used in Java?](http://stackoverflow.com/questions/355167/how-are-anonymous-inner-classes-used-in-java) – Chris K Sep 25 '14 at 15:32
  • See this http://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html#syntax-of-anonymous-classes – Wundwin Born Sep 25 '14 at 15:36

3 Answers3

1

This is not an abstract class

  new WaitForTestOutcomeThenAssert(this.assertionTemporalTolerance) {

         @Override
         public boolean checkCondition() {
             return getColumnValue(schema, table, columnName, whereClause) != null;
         }
   }

That is an anonymous class that extends WaitForTestOutcomeThenAssert. In other words, by writing that you are subclassing "WaitForTestOutcomeThenAssert" and instantiating it.

Claudio
  • 1,848
  • 12
  • 26
1

Try looking at anonymous classes. Here you have an anonymous class declaration that extends abstract class WaitForTestOutcomeThenAssert and overrides checkCondition method.

Aivean
  • 10,692
  • 25
  • 39
1

This is an Anonymous class. It's a shortcut to use Abstract class or Interface without having to explicitly write a subclass.

ortis
  • 2,203
  • 2
  • 15
  • 18