14 Inner Classes, Garbage Collector and Wrapper Classes 04 Aug 2020material - I - 04 Aug 2020 - Lecture8.1 Java - Innerclasses
14 Inner Classes, Garbage Collector and Wrapper Classes 04 Aug 2020material - I - 04 Aug 2020 - Lecture8.1 Java - Innerclasses
Java inner class or nested class is a class which is declared inside the class or
interface.
We use inner classes to logically group classes and interfaces in one place so that it can
be more readable and maintainable.
Additionally, it can access all the members of outer class including private data members
and methods.
1. class Java_Outer_class{
2. //code
3. class Java_Inner_class{
4. //code
5. }
6. }
1) Nested classes represent a special type of relationship that is it can access all the
members (data members and methods) of outer class including private.
Do You Know
o What is the internal code generated by the compiler for member inner class ?
o What are the two ways to create annonymous inner class ?
o Can we access the non-final local variable inside the local inner class ?
o How to access the static nested class ?
o Can we define an interface within the class ?
o Can we define a class within the interface ?
Type Description
Member Inner Class A class created within class and outside method.
Anonymous Inner A class created for implementing interface or extending class. Its name is decided by t
Class compiler.
Syntax:
1. class Outer{
2. //code
3. class Inner{
4. //code
5. }
6. }
Java Member inner class example
In this example, we are creating msg() method in member inner class that is accessing
the private data member of outer class.
1. class TestMemberOuter1{
private int data=30;
class Inner{
void msg(){System.out.println("data is "+data);}
}
public static void main(String args[]){
TestMemberOuter1 obj=new TestMemberOuter1();
TestMemberOuter1.Inner in=obj.new Inner();
in.msg();
}
}
Test it Now
Output:
data is 30
nice fruits
Output:
30
class Don
{
private int a=10;
void man()
{
class Fun
{
void msg()
{
System.out.println(a);
}
}
Fun l=new Fun();
l.msg();
}
public static void main(String[] args)
{
d1.man();
}
}
data is 30
In this example, you need to create the instance of static nested class because it has
instance method msg(). But you don't need to create the object of Outer class because
nested class is static and static properties, methods or classes can be accessed without
object.
1. class TestOuter2{
2. static int data=30;
3. static class Inner{
4. static void msg(){System.out.println("data is "+data);}
5. }
6. public static void main(String args[]){
7. TestOuter2.Inner.msg();//no need to create the instance of static nested class
8. }
9. }
Test it Now
Output:
data is 30
class Don
{
static int a=10;
static class Van
{
static void msg()
{
System.out.println("hello");
System.out.println(a);
}
}
public static void main(String[] args)
{
Van.msg();
}
}