Saturday, June 30, 2012

Nested Class

Todo :
1. how do nested classes act when overridden
  • Non-static nested classes are also called inner classes have access to other members of the enclosing class, even if they are declared private
  • Static nested classes do not have access to other members of the enclosing class
  • As a member of the OuterClass, a nested class can be declared private, public, protected, or package private

Why Use Nested Classes?

There are several compelling reasons for using nested classes, among them:
  • 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.

Non Static Nested Inner Class :

To instantiate an inner class, you must first instantiate the outer class. Then, create the inner object within the outer object with this syntax:
OuterClass.InnerClass innerObject = outerObject.new InnerClass();






An instance of InnerClass can exist only within an instance of OuterClass and has direct access to the
methods and fields of its enclosing instance.

Also, because an inner class is associated with an instance, it cannot define any static members itself.


Static Nested Class :

As with class methods and variables, a static nested class is associated
with its outer class. And like static class methods, a static
nested class cannot refer directly to instance variables or
methods defined in its enclosing class — it can use
them only through an object reference.

OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass();

Types of Nested Classes
Type Scope Inner
static nested class member no
inner [non-static] class member yes
local class local yes
anonymous class only the point where it is defined yes

______________________________________________

Note :
  1. Interfaces are never inner .
  2. Non Static inner classes cannot define static variables ex static int abc =0 will result in compile time error
  3. Non Static inner classes can define compile time constatns ex static final int abc=0


No comments:

Post a Comment