Code is usually written by inheriting a class or implementing an interface. However, sometimes some code is only used once, so there is no need to write a specific subclass or implementation class. You can useAnonymous internal class. The most common scenarios are:ThreadApplications.
1. Do not use anonymous internal classes
① Inheritance
Abstract class Player
{
Public abstract void play ();
}
Public class FootBallPlayer extends Player
{
Public void play ()
{
System. out. println ("soccer ");
}
}
Public class AnonymousInnerClassTest
{
Public static void main (String [] args)
{
Player p1 = new FootBallPlayer ();
P1.play ();
}
}
② Interface
Interface IPlayer
{
Public void play ();
}
Public class IPlayFootballImpl implements IPlayer
{
Public void play ()
{
System. out. println ("soccer ");
}
}
Public class AnonymousInnerClassTest
{
Public static void main (String [] args)
{
IPlayer ip1 = new IPlayFootballImpl ();
Ip1.play ();
}
}
Ii. Use anonymous internal classes
① Inheritance
Abstract class Player
{
Public abstract void play ();
}
Public class AnonymousInnerClassTest
{
Public static void main (String [] args)
{
Player p2 = new Player (){
Public void play ()
{
System. out. println ("playing basketball ");
}
};
P2.play ();
}
}
② Interface
Interface IPlayer
{
Public void play ();
}
Public class AnonymousInnerClassTest
{
Public static void main (String [] args)
{
IPlayer ip2 = new IPlayer (){
Public void play ()
{
System. out. println ("playing basketball ");
}
};
}
}
3. Applications in threads
There are two ways to implement the Thread: ① inherit the Thread class ② implement the Runnable interface. An example of using anonymous classes is provided:
Public class ThreadTest
{
Public static void main (String [] args)
{
// Inherit the Thread class
Thread thread = new Thread (){
@ Override
Public void run ()
{
While (true)
{
Try
{
Thread. sleep (1000 );
System. out. println (Thread. currentThread (). getName ());
System. out. println (this. getName ());
}
Catch (InterruptedException e)
{
System. out. println (e. getMessage ());
}
}
}
};
Thread. start ();
// Implement the Runnable interface
Thread thread2 = new Thread (new Runnable (){
@ Override
Public void run ()
{
While (true)
{
Try
{
Thread. sleep (1000 );
System. out. println (Thread. currentThread (). getName ());
}
Catch (InterruptedException e)
{
System. out. println (e. getMessage ());
}
}
}
});
Thread2.start ();
}
}