Monday, April 28, 2025

Java OO Tutorial - Inner Class - Nesting

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:

  1. An instance of OutsiderClass is created using the new keyword: OutsiderClass outObj = new OutsiderClass();
  2. The outsiderMethod() is called on the instance of OutsiderClass using the dot notation: outObj.outsiderMethod();
  3. An instance of InsiderClass is created using the new keyword and the constructor for InsiderClass, which is accessed using the instance of OutsiderClass created earlier: OutsiderClass.InsiderClass inObj = outObj.new InsiderClass();
  4. The insiderMethod() is called on the instance of InsiderClass using 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

No comments:

Post a Comment

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...