Create a new abstract class or interface, abstract class as long as there is an abstract method is an abstract class, the definition of the interface is: All of the methods are abstract methods, interfaces and abstract classes can not be directly instantiated, requires subclasses to implement
/* Anonymous Inner class:
1. Anonymous inner classes are actually simple styles of inner classes
2. The premise of defining an anonymous inner class must be to inherit a class or implement an interface
3. Format: New parent class or interface () {Defines the contents of a subclass (such as a function, etc.)}
4. In fact, the anonymous inner class is an anonymous subclass object. And the object is a little fat.
5. Anonymous internal class clocks should not be defined in more than 3 ways.
More code to build anonymous internal classes will be too much, very redundant.
*/
Public Abstract classAnimal { PublicString name; PublicString sex; Public Abstract voidrun (); Public Abstract voidEat (String name); /** * Syntax rules: Abstract cannot be used for private modification methods, cannot be used for final decoration methods abstract * cannot be sufficient with the decorated static method abstract cannot decorate member properties */ //This is not an abstract approach . PublicFinalvoideat () {}}
Then create a new subclass
Public classAnimaldemo {/** * Anonymous internal class use * * @param args*/ Public Static voidMain (string[] args) {
Anonymous internal classes are used, anonymous inner classes are abstract methods that implement the parent class, or all abstract methods that implement an interface Animal a=NewAnimal () {@Override Public voidrun () {System. out. println ("use the inner class to run"); } @Override Public voidEat (String name) {System. out. println ("use the inner class to run"+name); } }; A.eat (NewDate (). toString ()); //The following is the use of anonymous internal classes, equivalent to the above /** Animal a2=new Dog (); A2.eat ("Dog"); */Animal A3=NewCat (); A3.eat ("Fish"); }}//The following is the use of anonymous internal classes, equivalent to the aboveclassCat extends Animal {@Override Public voidrun () {System. out. println ("no use of internal class running"); } @Override Public voidEat (String name) {System. out. println ("without using the inner class, the cat eats"+name); }}
Learning of anonymous inner classes in Java