2

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.

Code Poet
  • 11,227
  • 19
  • 64
  • 97

3 Answers3

3

In Java these are called nested classes. There are several types of nested classes with different semantics. There is info at http://docs.oracle.com/javase/tutorial/java/javaOO/nested.html.

In your example that is an inner class, so its instances exist within an instance of the outer class.

jjmontes
  • 24,679
  • 4
  • 39
  • 51
3

Since the Contained class is not declared as static, it means that it can only exist within an instance of a Container class and hence has access to all of the methods and variables of Container.

If you had declared Contained as static, 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 of Container.

See Java inner class and static nested class for further details.

Community
  • 1
  • 1
Mansoor Siddiqui
  • 20,853
  • 10
  • 48
  • 67
0

This is a nested class. Its lifecycle is tied to the parent class. Read here for full understanding.

Petar Minchev
  • 46,889
  • 11
  • 103
  • 119