-1

Java shouldn't allow static methods within an inner class and yet this code compiles and runs. How is this possible?

class Test{
    
    static int j=20;
    public void m1() {
        class Inner{
            public static void m2() {
                System.out.println(j);
            }
        }
        Inner inner = new Inner();
        inner.m2();
    }
    
    public static void main(String[] args) {
        Test obj = new Test();
        obj.m1();
    }
}
1
  • "Java shouldn't allow static methods within an inner class" WHY not? Who says that? Commented Oct 13, 2024 at 13:04

2 Answers 2

4

The assumption is that your tutor is not up-to-date with the current (?) Java versions.

In fact it was not possible to have static methods in inner classes before Java 16, but with that Java version, it was allowed.

Refer to Why are static methods allowed inside a non-static inner class in Java 16? for some more information.

And the current Java version is Java 23 at the time I write this (2024-10-12).

Sign up to request clarification or add additional context in comments.

Comments

1

For Java 15 and older, your tutor would be correct. However, the rules changed in Java 16 with JEP 395: Records:

This JEP proposes to finalize the feature in JDK 16, with the following refinement:

  • Relax the longstanding restriction whereby an inner class cannot declare a member that is explicitly or implicitly static. This will become legal and, in particular, will allow an inner class to declare a member that is a record class.

As an aside, formally, the class Inner is actually called a local nested class, as it is a class local to your method, whether it's an inner class depends on if it is in a static or non-static method.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.