I’m looking to do something like this in Java:
public OuterClass {
public innerClass = new Object() {
private var1;
public void myMethod() {
...
}
}
}
and use it like this:
OuterClass outer = new OuterClass();
outer.innerClass.myMethod();
The reason is to basiclly namespace some methods within the OuterClass to keep things organised.
I know I could create an instance of innerClass and assign it to a public instance variable of OuterClass but I’m looking for an inline way of doing it like above example. I don’t want it to be possible to instantiate the innerClass more than once hence the inline approach.
This woule be similar to the following JavaScript:
var innerObject = new function() {
...
}
What you asked in the question title is possible, but unfortunately not what you really want.
In your code, the line with the declaration of the field
innerClassmisses a type for the field. With the rest of the code unchanged, there is only one possibility:Object.So your code would read like this:
This is actually possible, but calling the method
myMethodis not possible. When you accessouter.innerClass, this expression is of typeObject, which does not have a methodmyMethod, so the code won’t compile.You can however introduce an interface
MyInnerInterfaceand change the type of the field to
MyInnerInterface:Then accessing the method is possible. However you have the drawback of the additional interface.
Also this code is unusual and I wouldn’t consider it good. If you really want to have an inner class here, don’t use an anonymous class, but a real class:
Still, using an inner class for “scoping” accesses from the outside is something I wouldn’t do. Inner classes should usually be an implementing detail of the outer class and not be accessible to the public. Better think about how to separate your API into real co-existing classes (which of course might have references onto each other, and possibly access package-private members).