Example 1:
Import java. lang .*;
Public class Test {
Public static void main (String [] str)
{
Fun (new MyInterface () {public void Say ()
{
System. out. println ("this is temp interface ");
}});
Fun (new People () {public void Say ()
{
System. out. println ("this is temp class ");
}});
}
Static void Fun (MyInterface p)
{
P. Say ();
}
}
Interface MyInterface
{
Public void Say ();
}
Class People implements MyInterface
{
Public void Say ()
{
System. out. println ("this is People ");
}
}
Program output:
This is temp interface
This is temp class
Example 2:
Import java. lang .*;
Public class Test {
Public static void main (String [] str)
{
New Test (). TestFun ();
}
Static void Fun (MyInterface p)
{
P. Say ();
}
Void Why ()
{
System. out. println ("Why ");
}
Void TestFun ()
{
Fun (new MyInterface () {public void Say ()
{
Test. this. Why ();
Why ();
// If this sentence is added, it will enter an endless loop this. Say ();
// In summary, this represents a MyInterface type in this method, and the Test method can be used directly.
}});
}
}
Interface MyInterface
{
Public void Say ();
}
Program output: Why
Why
Example 3
Public class Test {
Static int Age = 123;
Public static void main (String [] str ){
System. out. println (myInterface. getClass ());
Fun (myInterface );
Age + = 1;
Fun (myInterface );
}
Static void Fun (MyInterface p ){
P. Say ();
}
Static MyInterface myInterface = new MyInterface (){
@ Override
Public void Say (){
System. out. println (Age );
}
};
}
Interface MyInterface
{
Public void Say ();
}
Program output:
Class Test $1
123
124
Example 4:
Public class Test {
Public static void main (String [] str ){
B. Test ();
}
Public void Run (){
System. out. println ("Test. Run ");
}
}
Class B {
Public static void Test (){
Test t = new Test (){
Public void Run (){
System. out. println (this. getClass ());
}
};
T. Run ();
Test t2 = new Test ();
System. out. println (t2.getClass ());
}
}
Program output: class B $1
Class Test
Fifth example:
Class Test {
Public static void main (String [] args)
{
A a = new (){
@ Override
Void Eat (){
Super. Eat ();
This. Say ();
System. out. println ("a. eat ");
}
};
A. Eat ();
System. out. println (a instanceof ));
System. out. println (a. getClass ()));
}
}
Class {
Void Say (){
System. out. println ("A. Say ");
}
Void Eat (){
System. out. println ("A. Eat ");
}
}
Program output:
A. Eat
A. Say
A. eat
True
Class Test $1