Example of member inner class that is invoked inside a class
In this example, we are invoking the method of member inner class from the display method of Outer class.
class Outer{ private int value = 70; class Inner{ void show(){ System.out.println("value is "+value ); } } void display(){ Inner in = new Inner(); in.show(); } public static void main(String args[]){ Outer obj = new Outer(); obj.display(); } }
output:
See in the directory there are the two following class files after compiling.
Outer.class
Outer$Inner.class
Internal code generated by the compiler for member inner class:
The java compiler creates a class file named Outer$Inner in this case. The Member inner class have the reference of Outer class that is why it can access all the data members of Outer class including private.
import java.io.PrintStream; class Outer$Inner { final Outer this$0; Outer$Inner() { super(); this$0 = Outer.this; } void show() { System.out.println((new StringBuilder()).append("value is ") .append(Outer.access$000(Outer.this)).toString()); } }
Example of member inner class that is invoked outside a class
In this example, we are invoking the show() method of Inner class from outside the outer class i.e. Test class.
//Program of member inner class that is invoked outside a class
class Outer{ private int value = 70; class Inner{ void show(){System.out.println("value is "+value);} } } class Test{ public static void main(String args[]){ Outer obj = new Outer(); Outer.Inner in = obj.new Inner(); in.show(); } }
output:
Rules for Inner Classes:
Following properties can be noted about Inner classes:
<OuterClassName> outerObj = new <OuterClassName>(arguments); outerObj.<InnerClassName> innerObj = outerObj.new <InnerClassName>(arguments);
<OuterClassName>.this.<variableName>
Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…
Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…
Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…
Technology has emerged a lot in the last decade, and now we have artificial intelligence;…
Managing a database is becoming increasingly complex now due to the vast amount of data…
Overview In this article, we will explore Spring Scheduler how we could use it by…