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?
Since they belong to the class, so they can be called to without creating the object of the class. Important Points: Static method(s) are associated with the class in which they reside i.e. they are called without creating an instance of the class i.e ClassName.
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.
Static inner classes can access static data members of the enclosing class. They can't access non-static data members; after all, you can create an instance of a static inner class without creating any instance of the enclosing 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.
The way you've defined MyRelatedClass
, you need to have an instance of MyClass
to be able to access/instantiate this class.
Typically in Java you use this pattern when an instance of MyRelatedClass
needs to access some fields of a MyClass
instance (hence the references to an "enclosing instance" in the compiler warning).
Something like this should compile:
public void doStuff() {
MyClass mc = new MyClass();
MyRelatedClass data = mc.new MyRelatedClass();
}
However, if a MyRelatedClass
instance does not need access to fields of it's enclosing instance (MyClass
's fields) then you should consider defining MyRelatedClass
as a static class, this will allow the original code you've posted to compile.
The difference in having a nested class (what you've posted) and a static nested class (a static class
within a class
) is that in the former, the nested class belongs to an instance of the parent class, while the latter has no such relationship - only a logical/namespace relationship.
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