Non static inner class:
- Defining inner class without static keyword.
- Non static members we access using instance.
- We can access inner class using outer class instance.
- We need to instantiate outer class by which we access non static inner class.
class Outer
{
void m1()
{
System.out.println("Outer class m1()...");
}
class Inner
{
void m2()
{
System.out.println("Inner class m2()...");
}
}
}
class Access
{
public static void main(String[] args)
{
Outer obj1 = new Outer();
obj1.m1();
Outer.Inner obj2 = obj1.new Inner();
obj2.m2();
}
}
- We can directly access the functionality by creating object as follows
- Instead of collecting the reference variable, we can access the method directly.
- We need to create object every time to access the functionality
class Outer
{
static class Inner1
{
void fun()
{
System.out.println("Inner1 class fun..");
}
}
class Inner2
{
void fun()
{
System.out.println("Inner2 class fun..");
}
}
}
class Access
{
public static void main(String[] args)
{
new Outer.Inner1().fun();
new Outer().new Inner2().fun();
}
}
We can instantiate the inner class directly as follows:
class Outer
{
class Inner
{
void fun()
{
System.out.println("Non static class non static fun..");
}
}
}
class Access
{
public static void main(String args[])
{
new Outer().new Inner().fun();
}
}
- Non static inner class can’t have static functionality.
- We access non static area only with permissions.
- Static members we cannot place inside restricted area.
class Outer
{
class Inner
{
static void fun()
{
System.out.println("not allowed...");
}
}
}