class
Nested class examples
In this example we shall show you how to create a nested class. To create a nested class we have performed the following steps:
- We have created class
MN
that has a methodf()
and an inner classA
. - Class
A
has also a methodg()
and another classB
. - Class has a method
h()
that callsg()
method ofA
andf()
method ofMN
. - Since
B
is a nested class it can access all members of all levels of the classes it is nested within. - We create a new instance of
MN
, and then using theMN
object we create a new instance ofA
, and usingA
object we create a new instance ofB
and call itsh()
method,
as described in the code snippet below.
package com.javacodegeeks.snippets.core; //Nested classes can access all members of all levels of the //classes they are nested within. public class NestedClass { public static void main(String[] args) { MN mna = new MN(); MN.A mnaa = mna.new A(); MN.A.B mnaab = mnaa.new B(); mnaab.h(); } } class MN { private void f() { System.out.println("Function MN.f()"); } class A { private void g() { System.out.println("Function A.f()"); } public class B { void h() { g(); f(); } } } }
Output:
Function A.f()
Function MN.f()
This was an example of how to create a nested class in Java.