Code is usually written by inheriting a class or implementing an interface, but sometimes some code is used only once, and there is no need to write a subclass or implementation class that can be used
Anonymous Inner classThe wording. The most frequently used scenarios are
ThreadsAspects of the application.
first, 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 ("play football");
}
}
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 ("play football");
}
}
public class Anonymousinnerclasstest
{
public static void Main (string[] args)
{
IPlayer ip1 = new Iplayfootballimpl ();
Ip1.play ();
}
}
Ii. use of 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");
}
};
}
}
third, the application of the thread
There are two ways to implement threading: ① inherits the Thread class ② implements the Runnable interface. Give a sample implemented with an anonymous class:
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 ();
Implementing 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 ();
}
}
Anonymous inner classes in Java