Nested classes are divided into two categories
- static Nested classes that are declared static are simply called static nested classes.
- non-static Non-static nested classes are called inner classes.
Nested classes can be declared public, private, protected.
Why use nested classes
- Suppose a situation where a class A is only used by another class B, in that situation it is no point of writing two classes separately. Class A can be embedded into class B as a nested class
- Suppose a situation one of class A's variables is used by class B otherwise that variable can be declared private. In such a case it is more appropriate to nest class B inside class A to protect encapsulation
Static nested classes
Static nested classes cannot access member variables of it's outer class directly. it can use them only through an object reference.
Syntax for creating an object in static object class
OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass();
Non Static nested classes or Inner Classes
Inner classes can access member variables of it's outer class directly even their access modifiers are private.
Syntax for creating an object in an inner class
OuterClass.InnerClass innerObject = outerObject.new InnerClass();
A sample code to try out
public class A { //start of outer class private int a=100; private String b="host"; public class B{ // start of inner class or non static nested class int e=a;//inner classes can access member variables directly even they are private }//End of inner class or non static nested class public static class C{ //start of static nested class A ob2 = new A(); String s =ob2.b;//static nested classes cannot access member variables directly, it should be done through an object of outer class } //End of start of static nested class public static void main(String s[]) { A ob1=new A(); A.B ob3=ob1.new B();//inner class object creation System.out.println(ob3.e); A.C ob4=new A.C();//static nested class object creation System.out.println(ob4.s); } }//End of outer class
No comments :
Post a Comment