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
MNthat has a methodf()and an inner classA. - Class
Ahas also a methodg()and another classB. - Class has a method
h()that callsg()method ofAandf()method ofMN. - Since
Bis 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 theMNobject we create a new instance ofA, and usingAobject we create a new instance ofBand 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.
