Bug 18147

Summary: Objects in instance initializer blocks are scoped too widely
Product: gcc Reporter: Casey Marshall <csm>
Component: javaAssignee: Not yet assigned to anyone <unassigned>
Status: RESOLVED FIXED    
Severity: normal CC: gcc-bugs, java-prs
Priority: P2 Keywords: rejects-valid
Version: 3.4.2   
Target Milestone: 4.3.0   
Host: i686-pc-linux-gnu Target: i686-pc-linux-gnu
Build: i686-pc-linux-gnu Known to work:
Known to fail: Last reconfirmed: 2005-07-23 05:32:35
Bug Depends on: 28067    
Bug Blocks:    

Description Casey Marshall 2004-10-25 18:46:26 UTC
If you declare an object within an instance initializer, you cannot declare
another object of the same name in a different instance initializer.

This description seems pretty opaque, so an example of correct code that GCJ
rejects is probably better:

-- init.java --
import java.util.HashMap;
class init
{
  private final HashMap _map1 = new HashMap();
  {
    Object foo = new Object();
    _map1.put ("foo!", foo);
  }

  private final HashMap _map2 = new HashMap();
  {
    Object foo = new Object();
    _map2.put ("bar!", foo);
  }
}
-- init.java --

GCJ exits with this error:

init.java:13: error: Variable `foo' is already defined in this method and was
declared `Object foo' at line 7.
       Object foo = new Object();
              ^
1 error
Comment 1 Andrew Pinski 2004-10-25 18:49:32 UTC
Confirmed, a workaround is to do something like this:
import java.util.HashMap;
class init
{
  {{
    Object foo = new Object();}
  }
  {
    Object foo = new Object();
  }
}

The reduced testcase:
import java.util.HashMap;
class init
{
  {
    Object foo = new Object();
  }
  {
    Object foo = new Object();
  }
}
Comment 2 Tom Tromey 2004-10-25 18:55:24 UTC
As a workaround you can put an extra block inside the
instance initializers:

{{ Object foo = ... }}

The bug here seems to be that gcj chains the statements
of each initializer block together when making finit.
Instead, however, it should treat each as a separate
block and chain the blocks together.  That is, an
instance initializer block introduces a new scope.
Comment 3 Tom Tromey 2007-01-09 20:46:37 UTC
All gcj front end bugs have been fixed by the gcj-eclipse branch merge.
I'm mass-closing the affected PRs.
If you believe one of these was closed in error, please reopen it
with a note explaining why.
Thanks.