Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested/Inner class in external file

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?

like image 376
Alp Avatar asked Jun 02 '11 18:06

Alp


People also ask

Can an inner class be accessed from outside package?

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.

Can we create object of a inner class outside of the outer 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.

How do you create an inner class instance from outside the outer class instance code?

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.


1 Answers

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.

like image 56
x4u Avatar answered Sep 24 '22 01:09

x4u