1

I'm currious why the following does create a subclass of the original class, changing the class' signature. (Here's a demo)

class Rextester
{  
    private final T2 t1;
    private final T2 t2;
    public static void main(String[] args) {
           new Rextester().test();
    }

    Rextester () {
        t1 = new T2() {{
            setFoo("foo");
            setBar("bar");
        }};

        t2 = new T2() ;
        t2.setBar("bar");
        t2.setFoo("foo");
    }

    private void test() {
        System.out.println("t1: " + t1.getClass()); // class Rextester$1
        System.out.println("t2: " + t2.getClass()); // class T2
    }
}



class T2 {
    private String foo;
    private String bar;

    public String getFoo() {
        return foo;
    }

    public void setFoo(String foo) {
        this.foo = foo;
    }

    public String getBar() {
        return bar;
    }

    public void setBar(String bar) {
        this.bar = bar;
    }

}

Why does t1 become a subclass of Rextester, while t2 stays what it should be? What good does this bring?

baao
  • 71,625
  • 17
  • 143
  • 203
  • 2
    Don't use 'double brace initialization', it is abusing syntax for what seems like a good trick, but can have serious repercussions in the form of memory leaks. – Mark Rotteveel Aug 29 '17 at 11:43
  • @MarkRotteveel thanks for the duplicate link. Didn't find it because I didn't knew the name. It actually just caused JAXB to be unable to marshal my class to xml, so another bad side effect... Is there any explanation on **why** this subclassing happens? – baao Aug 29 '17 at 11:45
  • 1
    You are approaching it from the wrong direction. This **abuses** anonymous classes and an instance initializer to give the **appearance** of a short form initialization. In other words, it is not a Java feature, it is just a **trick** that happens to use two Java language features in unintended ways and with potentially problematic side-effects (as you already noticed) depending on how and where it is used. – Mark Rotteveel Aug 29 '17 at 11:49
  • Ok, I get it... I'll read more about it, thanks for explaining! @MarkRotteveel – baao Aug 29 '17 at 11:50
  • 1
    `new Foo() {{}}` *doesn't* cause "automatic" subclassing - you get a subclass if you write `new Foo() {}` (just a single pair of braces), simply because that's how you declare an anonymous class. – Andy Turner Aug 29 '17 at 12:03

0 Answers0