Non
static nested classes are called inner classes
Syntax
class
OuterClass {
...
class
InnerClass {
...
}
}
How
to create an object to the inner class
OuterClass.InnerClass innerObject =
outerObject.new InnerClass();
Example
class Outer{ void print(){ System.out.println("I am in outer class"); } class Inner{ void print(){ System.out.println("I am in Inner class"); } } public static void main(String args[]){ Outer outerObj = new Outer(); Outer.Inner obj = outerObj.new Inner(); obj.print(); } }
Output
I am in Inner class
There
are two additional types of inner classes.
Those
are:
Some
points to Remember
1.
Inner class is associated with an instance, it cannot define any
static members itself. Defining static variable inside inner class
causes the compiler error
class Outer{ class Nested{ static int a = 100; } }
Outer.java:3: error: Illegal static declaration in inner class Outer.Nested
static int a = 100;
^
modifier 'static' is only allowed in constant variable declarations
1 error
2.
You can define static constants in the inner class, but not static
variables.
class Outer{ class Nested{ static final int a = 100; } }
3.
Defining static methods inside inner class causes compiler error
class Outer{ class Nested{ static void print(){ } } }
When
you tries to compile the above program, compiler throws the below
error
Outer.java:3: error: Illegal static declaration in inner class Outer.Nested static void print(){ ^ modifier 'static' is only allowed in constant variable declarations 1 error
4.
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
Example
class Outer{ String name; void setName(String name){ this.name = name; } class Inner{ public void print(){ System.out.println(this.name); System.out.println(Outer.this.name); } String name; void setName(String name){ this.name = name; } public String toString(){ return name; } } public static void main(String args[]){ Outer obj = new Outer(); obj.setName("Outer Class Object"); Outer.Inner in = obj.new Inner(); in.setName("Inner Class Object"); in.print(); } }
Output
Inner Class Object Outer Class Object
No comments:
Post a Comment