Can static blocks and variables be used inside anonymous inner classes in Java?

54 Views Asked by At

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)

enter image description here

But in the YouTube video or online compiler (it gives this error)

enter image description here

Now what is the reason for this difference?

And Do static blocks and static variables work inside anonymous inner classes or not?

1

There are 1 best solutions below

1
rzwitserloot On

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.