Two implementations of anonymous classes in Java

  • 2020-06-01 09:53:34
  • OfStack

Using anonymous inner classes makes the code cleaner, more compact, and more modular. An inner class can access 1-slice member variables and methods externally, including private ones, whereas an implementing interface or an inherited class cannot. But that's not the point. What I'm saying is very simple. There are two ways to implement anonymous inner classes: first, to inherit a class and override its methods; Second, implement an interface (which can be multiple) and implement its methods. The following is illustrated by the code:


public class TestAnonymousInterClass{  
 public static void main(String args[]){  
  TestAnonymousInterClass test=new TestAnonymousInterClass();  
  test.show();  
 }  
 // Constructed in this method 1 Two anonymous inner classes   
 private void show(){  
  Out anonyInter=new Out(){//  Gets an anonymous inner class instance      
   void show(){// Overrides the methods of the parent class   
    System.out.println("this is Anonymous InterClass showing.");  
   }  
  };  
  anonyInter.show();//  Call its method   
 }  
}   
//  This is a 1 Three existing classes, anonymous inner classes, will get another implementation by overriding their methods   
class Out{  
 void show(){  
  System.out.println("this is Out showing.");  
 }  
}

The output result of the program is:

this is Anonymous InterClass showing.

So as you can see here, anonymous inner classes have their own implementation. It's easy to use anonymous inner classes because I need a little bit of a special implementation here, so I've given the implementation here as well. And I'm going to get an instance of it right here, and I'm going to call its methods.

Interface, just replace the parent class with the interface, there is no need to give the code.

Let's not forget our purpose when using anonymous inner classes, we just want to have a special implementation of a class here. Instead of thinking too much, write other methods anonymously. Your own methods written in anonymous inner classes are not visible. There is no point in doing this, and certainly no point in doing this. This is just to tell beginners not to think too much about anonymous inner classes, but to think that anonymous inner classes are methods that override the parent class or interface.

Anonymous inner classes don't have a name, so we can't get their type, but use it as a superclass or interface type.


Related articles: