Nested classes are divided into two categories:
- static. They are simply called static nested classes.
- non-static. They are called inner classes.
Reasons for using nested classes:
- It is a way of logically grouping classes that are only used in one place.
- It increases encapsulation.
- Nested classes can lead to more readable and maintainable code.
Notes
- Access modifiers (private/public/protected) have no effect on inner classes - independant of the modifier, the classes are public.
- Inner classes could access members of outer class, no meter of their access modifier.
OuterClass.ProtectedStaticInnerClass c =
new OuterClass.ProtectedStaticInnerClass(); // FINE
OuterClass.PublicStaticInnerClass d =
new OuterClass.PublicStaticInnerClass(); // FINE
OuterClass outer = new OuterClass();
OuterClass.ProtectedInnerClass a2 = outer.new ProtectedInnerClass(); // FINE
OuterClass.PublicInnerClass b2 = outer.new PublicInnerClass(); // FINE
Note: class definitions are given below.
WRONG usage
Here are examples of wrong usage of inner classes out of the outer class. They makes compile time errors:
OuterClass.ProtectedInnerClass a1 = new OuterClass.ProtectedInnerClass(); // ERROR
OuterClass.PublicInnerClass b1 = new OuterClass.PublicInnerClass(); // ERROR
Code base
public class OuterClass {
private int outerPrivateInt;
private static int outerPrivateStaticInt;
protected class ProtectedInnerClass {
protected int protectedProtectedMember = outerPrivateInt;
// in the inner class you could access members of outer class,
// even if they are declared private
public int protectedPublicMember;
int dublicate;
}
protected class PublicInnerClass {
protected int publicProtectedMember;
public int publicPublicMember;
int dublicate;
}
public static class PublicStaticInnerClass{
public int psic;
// public int psic = outerPrivateInt; -> ERROR
// in the inner STATIC class you NOT could access members of
// outer class
public int psic2 = outerPrivateStaticInt;
// in the inner STATIC class you have access to static
// members of outer class
}
protected static class ProtectedStaticInnerClass{
public int psic;
}
public OuterClass(){
// do something
}
}
No comments:
Post a Comment