Why you need to use an inner class.
The reason for using the inner class is that each inner class can inherit independently from one (interface) implementation, so no matter whether an external class has inherited an implementation of an (interface), it has no effect on the inner class. In fact, the inner class effectively implements "multiple inheritance", that is, the inner class allows multiple non-interface types to be inherited.
We know that internal classes automatically have access to all members of the external class, so how does this work? When an external class object creates an internal class object, the inner class object is bound to secretly capture a reference to that outer class object. Then, when you access the members of the external class, you use that reference to select the members of the external class. Of course, the details are compiler processing, and the inner class here is non-static.
To create an object of an inner class, instead of referencing the name of the outer class in the way it was intended to dotnew, you must use an object from an external class to create an object of the inner class. As in the following example:
public class dotnew{
public class inner{
}
public static void Main (string[] args) {
Dotnew DN =new dotnew ();
Dotnew.inner dni=dn.new Inner ();
}
}
However, if you create a nested class (Static inner Class), then you do not need an external class object reference, as in the following example:
Package innerclassdotnew;
public class Innerdotnew {
Innerdotnew () {
System.out.println ("innerdotnew");
}
Static Class staticinner{
Staticinner () {
System.out.println ("Static inner Class");
}
Class inner{
Inner () {
System.out.println ("Normal Inner class");
}
public static void Main (string[] args) {
innerdotnew idn=new innerdotnew ();
Innerdotnew.inner dninner=idn.new Inner ();
/*compile Error:
No enclosing instance of type Innerdotnew is accessible.
Must qualify the allocation with a enclosing instance to type Innerdotnew
(e.g. X.new A () where x is A instance of innerdotnew). *
///innerdotnew.inner dninner=new Inner ();
Innerdotnew.staticinner Staticinner =new Staticinner ();
}
}
/*output/
Innerdotnew
Normal Inner class
Static Inner class