views:

145

answers:

3

I could swear I saw an object being created this way. What does somethingelse do?

+2  A: 

It seems that new JSomething().somethingelse is just a field access. Maybe a badly written static access of JSomething.somethingelse. For example Color color = new Color(0).black; instead of Color color = Color.black;.

kd304
A: 

somethingelse in this context would be an instance of JSomething, which is contained within a JSomething.

akf
+4  A: 

Taking it quite literally, it can be that the class JSomething has a field called somethingelse that is of type JSomething:

class JSomething {
    JSomething somethingelse;
}

In that case, the reference to the JSomething called somethingelse inside the JSomething can be obtained by the following:

JSomething something = new JSomething().somethingelse;

However, I suspect that this was seen as part of a design pattern called the builder pattern -- where a method call returns an instance of the same type.

For example, take the StringBuilder.append method -- it returns a StringBuilder. Therefore, it would be possible to do the following:

StringBuilder sb = new StringBuilder("Hello").append("World!");
coobird