Explain Codes LogoExplain Codes Logo

Is not an enclosing class Java

java
inner-classes
static-nested-classes
encapsulation
Alex KataevbyAlex Kataev·Aug 23, 2024
TLDR

If you encounter "is not an enclosing class", it's likely you're trying to instantiate an inner class incorrectly. Associate the inner class with an existing outer class instance like so:

OuterClass outer = new OuterClass(); OuterClass.InnerClass inner = outer.new InnerClass();

In other words, bind the inner class instance with an outer class instance, providing the inner class the right context.

Know thy inner class: Static vs Non-Static

Understanding static vs non-static inner classes in Java can help you avoid such errors. Let's break it down in a few points.

Static Inner Class

A static inner class:

  • Does not have access to the instance variables of the outer class.
  • Implies, that it can exist independently of the outer class.
class OuterClass { static class StaticNestedClass { // Like a cat - needs you, but pretends it doesn't 🐈 } }

Non-Static Inner Class

A non-static inner class, or simply an inner class:

  • Can interact with the instance variables or methods of the outer class.
  • Is like your secretive journal - it knows the outer class inside out!
class OuterClass { class InnerClass { // Like a dog - best friends with the outer class 🐕 } }

Instantiating inner classes

OuterClass outerInstance = new OuterClass(); OuterClass.InnerClass innerInstance = outerInstance.new InnerClass();

Notice how we need to create an outer instance first and then we create the inner instance.

Fielding with Modifiers

We can attach modifiers such as final or static final for variables that don't depend on the outer instance. It optimizes the performance and adds clarity.

Getting a Grip of Scope and Visibility

Define access scope and visibility while using inner classes:

  • Use getters in the outer class to instantiate inner class and access its members.

Meeting Static Nested Classes

To recognize static nested classes:

  • Use the outer class name followed by a .
  • They don't need an outer instance to exist.
  • However, they can't directly access non-static members of the outer class.

Decoding Common Errors

The error "Shape is not an enclosing class" could be a result of:

  • A syntax error in object creation of inner classes.
  • Misaligned design patterns within the classes, needing restructuring for optimal results.

Utilization and Design of Inner Classes

Improving encapsulation

Utilize inner classes to enhance encapsulation and reusability:

  • Good use of inner classes can result in a cleaner codebase with neatly defined functionalities.

Consider design implications

Sometimes, the usage of inner classes can cause design complications:

  • Restructure the code to incorporate necessary changes such as making inner classes static or creating correct instances.