I’m new to Java (have experience with C#),
this is what I want to do:
public final class MyClass
{
public class MyRelatedClass
{
...
}
}
public class OtherRandomClass
{
public void DoStuff()
{
MyRelatedClass data = new MyClass.MyRelatedClass();
}
}
which gives this error in Eclipse:
No enclosing instance of type BitmapEffects is accessible. Must qualify the allocation with an enclosing instance of type BitmapEffects (e.g. x.new A() where x is an instance of BitmapEffects).
This is possible in C# with static classes, how should it be done here?
In response to the comments about packaging multiple classes in one file: unlike .NET, most implementations of java enforce a strict correlation between the name of public class type and the name of the file the class type is declared in. It’s not a hard requirement, but not used a system where the correlation is not enforced. The JLS – 7.6 Top Level Type Declarations says this:
See this SO question: multiple class declarations in one file
If you are looking to create a namespace to enclose your related classes, then using static inner classes are what you need. The static declaration does not mean one instnace – they can still be instantiated – the
staticmeans that they can be instantiated without needing a reference to the enclosing class. As the enclosing class is just for grouping, and not data, you are safe making it a static. To make it clearer that the enclosing class is just for grouping, you should declare it as aninterface, so that it cannot be instantiated and has no implementation details.Although personally, I would refrain from doing this – in Java, packages are used to enforce a namespace. Using inner classes for this quickly becomes cumbersome. (I have tried it!)