1 //12 NewObject () {3 voidShow () {4System.out.println ("Show Run"); 5 }6 }.show ();7 //28Object obj =NewObject () {9 voidShow () {TenSystem.out.println ("Show Run"); One } A }; - obj.show (); - the
The second compilation failed because the anonymous inner class is a subclass object, and when the obj reference to object is pointed to, it is promoted to the type of object, and compile time checks if there is a show method in the object class, so the compilation fails.
-----------
1 classInnerClassDemo6 {2+Static)classinner{3 voidShow () {}4 }5 Public voidmethod () {6 This.NewInner (). Show ();//can be7 }8 Public Static voidMain (string[] args) {//static does not allow this9this.NewInner (). Show ();//error, the inner class needs to be defined as staticTen } One}
---------------------------
1 Interfaceinter{2 voidShow ();3 }4 classouter{//the code in the outer class is complemented by an anonymous inner class. 5 Public StaticInter Method () {6 return NewInter () {7 Public voidShow () {}8 };9 }Ten } One classInnerClassDemo7 { A Public Static voidMain (string[] args) { - Outer.method (). Show (); - /* the Outer.method (): It means: There is a method called "methods" in Outer, and this method is static. - Outer.method (). Show (): When the Outer class invokes a static method, the result of the operation ends with a call to the Show method, which means that the method () algorithm finishes the operation of an object, and the object is of type Inter. - */ -function (NewInter () { + Public voidShow () {} -});//the anonymous inner class is passed as a parameter to the method. + } A Public Static voidfunction (Inter in) { at in.show (); - } -}
Anonymous inner class-details