Anonymous internal class with creation parameters

xiaoxiao2021-03-06  15

Package tigers;

class Super {protected String name; public Super (String name) {this.name = name;} public void append (int ch) {// do nothing} public String getName () {return this.name;}} public class Tiger35 {Public Super Getsuper (String Name) {Return New Super (Name) {PUBLIC VOID APPEND (INTCCH) {Super.Name = "*" CH;} PUBLIC STRING TOSTRING () {return "an anonymous internal class:" ;}};} Public static void main (String [] args) {Tiger35 T35 = new Tiger35 (); super s = t35.getsuper ("bitan"); for (char c = 'z'; c <'a' ; C ) {s.append (c);} system.out.println (s s.getname ());}}

result:

An anonymous internal class: Bitan * 90 * 91 * 92 * 93 * 94 * 95 * 96

in conclusion:

First, because there is no name in anonymous internal class, it does not construct a function. Because there is no constructor, it must be instantiated to the constructor of the parent class, in other words: Anonymous internal class completely handed the task of the creation object to the parent class.

Second, create a new method in anonymous internal classes is not much significant, but it can achieve the magical effect by overwriting the parent class, as shown in the example. This is an embodiment of polymorphism.

Third, because there is no name in the anonymous internal class, it is unable to make down forced type conversion, and the type of variable reference to an anonymous internal class object must be its direct or indirect parent class type.

转载请注明原文地址:https://www.9cbs.com/read-46489.html

New Post(0)