I am wondering how come I can reach inner class directly from outer type as if it is a static member like :
public class Hello {
public class UnderHello
{
void runObject()
{
}
}
}
So when I reach the UnderHello
public class SomeOtherClass {
public void ClickOnMe()
{
Hello.UnderHello //this is shown by auto-complete
}
}
I was expecting something like this :
public class SomeOtherClass {
public void ClickOnMe()
{
Hello world = new Hello();
world.UnderHello // after creating an instance, then UnderHello should now be seen by auto-complete
}
}
If UnderHello
was开发者_JS百科 a static
class, it would make sense since I can reach static members of a class by directly from Class itself rather than creating instance of the outer class. But it is inner-class.
I am confused.
Can somebody help me now?
Thanks.
The syntax is this:
new Hello().new UnderHello();
And since this is awfully confusing, I think it shouldn't be used. Non-static inner classes should be private (or better: package-scoped) and should be instantiated from the outer class only.
Hello.UnderHello
is correct, because that is the name of the class.
This does not mean, however, that you can actually create instances of this inner class without an instance of the outer class.
Hello.UnderHello x = new Hello.UnderHello(); // this will not work
// at least not from everywhere
If UnderHello was a static class, it would make sense since I can reach static members of a class by directly from Class itself rather than creating instance of the outer class.
The class definition itself is always static, if you will. You do not need an instance to refer to it (and the class definition also does not change with the outer instance).
If UnderHello
was a field or a method, then yes, you would need an instance to access it, unless it was declared static
.
You can type Hello.UnderHello because it's the name of the type, but you can't for instance initialize it using new Hello.UnderHello()
, you need
Hello hello = new Hello();
hello.new UnderHello();
i think ,because UnderHello is a nested class with in the Hello Class Scope so there is no other way to reach to this class except through parent class.
Its like Namespace.ClassName
Since UnderHello
isn't a static inner class, you can only instantiate it like this:
new Hello().new UnderHello();
But it's type is Hello.UnderHello
.
精彩评论