Do static blocks and static variables work inside anonymous inner classes in java?
Hello, I was following a video explanation on YouTube and it was talking about the static blocks and the static variables and that you cannot use them inside the anonymous inner classes
the code
package Anonymous;
public class main {
public static class TestClass {
public void TestMethod() {
System.out.println("test");
}
}
public static void main(String[] args) {
TestClass test = new TestClass() {
static int p = 5;
final static int y = 5;
static {
}
@Override
public void TestMethod() {
System.out.println("test 2");
}
};
test.TestMethod();
}
}
Now when I run on my computer (does not give an error)
But in the YouTube video or online compiler (it gives this error)
Now what is the reason for this difference?
And Do static blocks and static variables work inside anonymous inner classes or not?


Up to java version 15, you can't do that. Starting with java 16, you can. Clearly on your computer you are running java 16 or higher, and the youtube thing is running 15 or lower.