Non-static inner class cannot have static members.
Isn't listed as a correct response. Is that an error?
Code: Select all
class Test{
class X{
//static int i = 1; //error
final static int j = 2; //ok
}
}
Moderator: admin
Code: Select all
class Test{
class X{
//static int i = 1; //error
final static int j = 2; //ok
}
}
duh! Sorry. My brain must have been switched off when I posted that:)admin wrote:Because, as your example shows, and as we discussed in viewtopic.php?f=2&t=4519, they can be as long as they are constant variable.
Code: Select all
public class App {
static Runnable staticRef;
static {
staticRef = new Runnable() {
@Override
public void run() {
// System.out.println(App.this); Wont compile
}
};
}
}
Code: Select all
var clazz = App.staticRef.getClass();
var newInst = clazz.getDeclaredConstructors()[0].newInstance();
An anonymous class is always an inner class (§8.1.3); it is never static (§8.1.1, §8.5.1).
Good to know.andrew1584 wrote: ↑Sat Oct 28, 2023 10:15 amWhy is this marked as a correct answer?
"Anonymous classes cannot be static."
Difference between static and non-static classes - non-static classes initiated in context of outer class instance and always have a reference to this instance. Anonymous class can be initiated in a static block - in this case it wont have any reference to outer class instance:
Anonymous class doesn't have an explicit constructor, but you can use reflection to create an instance of class without Outer class instance:Code: Select all
public class App { static Runnable staticRef; static { staticRef = new Runnable() { @Override public void run() { // System.out.println(App.this); Wont compile } }; } }
So it behaves as any other static inner class.Code: Select all
var clazz = App.staticRef.getClass(); var newInst = clazz.getDeclaredConstructors()[0].newInstance();
I found that before JLS was explicitly saying:An anonymous class is always an inner class (§8.1.3); it is never static (§8.1.1, §8.5.1).
https://docs.oracle.com/javase/specs/jl ... jls-15.9.5
However, JLC SE17 doesn't have this statement anymore:
https://docs.oracle.com/javase/specs/jl ... jls-15.9.5
Users browsing this forum: No registered users and 11 guests