How to Initialise Non-static Member Class in Java


In this example we will show two methods to access the non-static inner class, and both methods require the creation of top-level class objects.

Source Code

1 Outer)

package com.beginner.examples;

public class Outer {
	
	public class Inner{
		
		public void show() {
			System.out.println("The member methods in the inner class are called");
		}
		
	}
	
	public Inner getInner() {
		
		return new Inner();
	}
	

}

2 Test)

package com.beginner.examples;

public class Test {

	public static void main(String[] args) {
		
		Outer.Inner inner = new Outer().getInner();
		inner.show();
		
		Outer.Inner inner2 = new Outer().new Inner();
		inner2.show();
		

	}

}

Output:

The member methods in the inner class are called
The member methods in the inner class are called
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments