非静态方法中实现私有抽象静态类的匿名类是否持有外部类引用?
Concept Class? Short Answer: No, it does NOT.
Detailed Explanation
Let's break this down clearly, based on Java's core rules for inner classes and anonymous classes:
Static inner classes have no implicit outer class ties
YourInnerclass is markedstatic—this makes it a standalone nested class that’s only tucked insideConceptfor structure, not because it depends on aConceptinstance. Any subclass of a static inner class (including your anonymous subclass here) inherits this independence: it doesn’t automatically carry a reference to the outerConceptclass.Anonymous classes only hold outer references when necessary
An anonymous class will only get an implicit outer class reference if two conditions are met:- It’s created in a non-static context (like your
func()instance method), AND - It accesses instance members of the outer class (e.g.,
Concept.this.someInstanceFieldor an instance method) OR it’s a subclass of a non-static inner class.
In your code, the anonymous subclass of
Inneronly implementsbar()to return a newObject—it never interacts with any instance-specific part ofConcept. There’s no reason for it to hold a reference to aConceptinstance, so Java doesn’t generate one.- It’s created in a non-static context (like your
Quick Verification Tip (If You Want to Confirm)
If you’re curious to see this in action:
- Use a Java decompiler (like the built-in
javaptool) to inspect the anonymous class’s bytecode. You’ll notice its constructor doesn’t take aConceptinstance as a parameter—unlike anonymous classes that do hold outer references, which always have this parameter to pass the outer instance. - Try adding a reference to a
Conceptinstance member inbar()(e.g.,return Concept.this;). You’ll see the compiler now generates code to pass the outerConceptinstance to the anonymous class—but this doesn’t happen in your original code.
内容的提问来源于stack exchange,提问作者Brian K

