An inner class is a class that is defined within the body of another class.
class OutsiderClass {
public void outsiderMethod() {
System.out.println("I am from outsiderMethod");
}
class InsiderClass {
public void insiderMethod() {
System.out.println("I am from insiderMethod");
}
}
}
public class Main {
public static void main(String[] args) {
OutsiderClass outObj = new OutsiderClass();
outObj.outsiderMethod();
OutsiderClass.InsiderClass inObj = outObj.new InsiderClass();
inObj.insiderMethod();
}
}
Here's a detailed explanation of the code, block by block:
class OutsiderClass {
public void outsiderMethod() {
System.out.println("I am from outsiderMethod");
}
class InsiderClass {
public void insiderMethod() {
System.out.println("I am from insiderMethod");
}
}
}
The above code defines two classes: OutsiderClass and InsiderClass. InsiderClass is an inner class defined inside OutsiderClass.
OutsiderClass has one method outsiderMethod() that simply prints out a message to the console using System.out.println().
InsiderClass has one method insiderMethod() that also prints out a message to the console.
public class Main {
public static void main(String[] args) {
OutsiderClass outObj = new OutsiderClass();
outObj.outsiderMethod();
OutsiderClass.InsiderClass inObj = outObj.new InsiderClass();
inObj.insiderMethod();
}
}
The above code is the Main class, which contains the main() method. Inside the main() method:
- An instance of
OutsiderClassis created using thenewkeyword:OutsiderClass outObj = new OutsiderClass(); - The
outsiderMethod()is called on the instance ofOutsiderClassusing the dot notation:outObj.outsiderMethod(); - An instance of
InsiderClassis created using thenewkeyword and the constructor forInsiderClass, which is accessed using the instance ofOutsiderClasscreated earlier:OutsiderClass.InsiderClass inObj = outObj.new InsiderClass(); - The
insiderMethod()is called on the instance ofInsiderClassusing the dot notation:inObj.insiderMethod();
When this code is run, it will output the following to the console:
I am from outsiderMethod
I am from insiderMethod