Todo :
1. how do nested classes act when overridden
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:
______________________________________________
Note :
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 declaredprivate
,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 ofInnerClass
can exist only within an instance ofOuterClass
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();
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 :
- Interfaces are never inner .
- Non Static inner classes cannot define static variables ex static int abc =0 will result in compile time error
- Non Static inner classes can define compile time constatns ex static final int abc=0
No comments:
Post a Comment