I am new to Java. I’m a C++ programmer, reading some Java code. I have this class definition:
class Container {
long ID;
class Contained {
void foo(){
long parentID = ID;
}
}
}
I see that Contained can access any member of the Container class, simply by name.
I have one question:
What is going on here? In C++ these classes would be unrelated. But in Java, it seems, the contained class object seems to be implicitly tied to the instance of the parent class object.
Thanks
Manish
PS: Sorry, I know I could pick up a book on Java, but I was hoping someone could help me.
Since the
Containedclass is not declared asstatic, it means that it can only exist within an instance of aContainerclass and hence has access to all of the methods and variables ofContainer.If you had declared
Containedasstatic, it would imitate the C++ usage that you’re more used to — that is, you could have an instance of the nested class without having an instance ofContainer.See Java inner class and static nested class for further details.