Anonymous Class
Inner Class
Java
Java Basics
Local Class
Nested Class
Nested Classes
Nested Classes in java
Nested Classes in java
Nesting a class inside another class is called Nested class. Ha ha..Kidding. But its true.
Writing a class within another class in java is referred as Nested class in Java.
Nested class is categorized into two types :
1. Static Nested Class - Nested class which are static.
2. Inner Class - If they are not static.
class OuterClass { ... static class StaticNestedClass { ... } class InnerClass { ... } }
*Nested class is considered as a member of the enclosing class, so that it may be declared private, public, protected, or package private.
Inner Class (non static)
Inner classes can access members of the enclosing class. even if they are declared private.
class OuterClass { // other member fn() and variables class InnerClass{ // member fn() and variables of inner class } }
Here the instance creation of the InnerClass is really diffrent.
OuterClass outer = new OuterClass(); OuterClass.InnerClass innerObject = outer.new InnerClass();
Note :
1) The instance of the inner class is associated with the instance of the Outer class
2) Since the inner class instance is associated with the instance of outer class, the inner class is not allowed to have static variables, but static final variable is allowed.
3) An instance of the inner class only exists with the instance of the outer class.
Please go through the code sample for better understanding.
package com.demo; public class OuterClass { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } class InnerClass { private String nestedName; public String getNestedName() { return nestedName; } public void setNestedName(String nestedName) { this.nestedName = nestedName; } @Override public String toString() { return "InnerClass [nestedName=" + nestedName + ", getNestedName()=" + getNestedName() + "]"; } } public static void main(String... args) { OuterClass outer = new OuterClass(); outer.setName("I am outer"); System.out.println(outer.getName()); // outer class instance accessing the member fn() OuterClass.InnerClass innerObject = outer.new InnerClass(); // creating the instance of the inner class innerObject.setNestedName("http://benoyprakash.blogspot.com"); System.out.println(innerObject); } }
Output
I am outer InnerClass [nestedName=http://benoyprakash.blogspot.com, getNestedName()=http://benoyprakash.blogspot.com]
Inner Classes are of two types :
1) Local Class
2) Anonymous Class
No comments