Monday, May 27, 2013

Nested Classes

As the name suggests, nested classes are classes which are defined within an outer parent class. The following example creates a nested class called NestedClass which is encapsulated in the outer class called OuterClass.

    class OuterClass
        public int nOuterValue;
        public class NestedClass
            public int nInnerValue;

To create an instance of the nested class we need to define the class name preceded by the outer class and a dot as follows.
    OuterClass objOuter = new OuterClass();
    objOuter.nOuterValue = 10;
    OuterClass.NestedClass objNested = new OuterClass.NestedClass();
    objNested.nInnerValue = 5;

The above example creates an instance of both the outer class and the nested class and assigns values to the member variables of both the outer and the nested class.

In this example I have defined the member variables with public scope just to explain the concept of Nested class, member variables should always be declared as private and we should define appropriate public get/set properties to access the variables.

Search Flipkart Products:

No comments: