I have a class MyClass
and an inner class MyNestedClass
like this:
public class MyClass { ... public class MyNestedClass { ... } }
Both classes are very long. Because of that i'd like to seperate them in two different files, without breaking the hierarchy. This is because the nested class shouldn't be visible to the programmer who uses MyClass.
Is there a way to achieve that?
Inner Class You just need to write a class within a class. Unlike a class, an inner class can be private and once you declare an inner class private, it cannot be accessed from an object outside the class.
An instance of InnerClass can exist only within an instance of OuterClass and has direct access to the methods and fields of its enclosing instance. To instantiate an inner class, you must first instantiate the outer class.
To instantiate an inner class, you must first instantiate the outer class. Then, create the inner object within the outer object with this syntax: OuterClass. InnerClass innerObject = outerObject.
You can make the inner class package private which means that it will only be accessible from other classes in exactly the same package. This is also done quite frequently for hidden classes inside the standard JDK packages like java.lang
or java.util
.
in pkg/MyClass.java
public class MyClass { ... }
in pkg/MyHiddenClass.java
class MyHiddenClass { final MyClass outer; MyHiddenClass( MyClass outer ) { this.outer = outer; } ... }
Now when you want to access methods or variables of the outer class you need to prefix them with outer.
but you get essentially the same functionality as before when the reference to the outer instance was synthetically created by the compiler.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With