Using final object in anonymous inner class results in null
<p>I have a method that contains the following code:</p>

<pre><code>public void myMethod(){
    final MyDto expectedtDto = new MyDto();

    MyRepository reposWithMock = new MyRepository(){
        protected MyDao createDao(){

            return new MyDao() {
                public MyDto someMethod(){
                   return expectedtDto;
                }
            };

        }
    };

  reposWithMock.doSomethingWithDao();
}
</code></pre>

<p><code>MyRepository.createDao()</code> is called from the constructor of <code>MyRepository</code>. 
<code>MyDao.someMethod()</code> is called from <code>MyRepository.doSomethingWithDao()</code>.</p>

<p>However, the <code>MyDao().someMethod()</code> returns <code>null</code> instead of the <code>expectedDto</code></p>

<p>Any idea why this is?</p>

<p>For clarification, some real working code:</p>

<pre><code>package nl.tests;

public class TestAnon {
  static class MyDao {
    private int value;

    public MyDao(int value) {
        this.value = value;
    }

    public int getValue() {
        return value;
    }
  }

  static class Repository {
    private MyDao dao;

    public Repository() {
        dao = createDao();
    }

    protected MyDao createDao(){
        return new MyDao( 4 );
    }

    public MyDao getDao(){
        return dao;
    }
  }

  public static void main(String[] args) {
    final MyDao testDao = new MyDao(8);

    Repository repos = new Repository() {
        protected MyDao createDao() {
            if ( testDao == null ) {
                System.out.println( "Error ");
                return new MyDao(0);
            }
            return testDao;
        }
    };

    System.out.println( "Dao :" + repos.getDao().getValue() );
  }
}
</code></pre>

<p>This results in :</p>

<pre><code>Error 
Dao :0
</code></pre>

<p>Some additional information: I currently (have to) work with java 1.4. 
My development environment is Rational Application Developer 7.</p>

<p>Addendum, to the given (and accepted answer). For the below code I've made the createDao() method public :</p>

<pre><code>public static void main(final String[] args) {        
    final MyDao testDao = new MyDao(8);    


    Repository repos = new Repository() {
        public MyDao createDao() {

            if ( testDao == null ) {
                System.out.println( "Error ");
                return new MyDao(0);
            }
            return testDao;
        }
    };

    System.out.println( "Dao :" + repos.getDao().getValue() );
    System.out.println( "Dao :" + repos.createDao().getValue() );
}
</code></pre>

<p>Returns:</p>

<pre><code>Error
Dao :0
Dao :8
</code></pre>
