Java programming ideology:
A closure is an callable object that records some information from the creation of its scope, with this definition, we can see that the internal class is an object-oriented closure, because it not only contains information about the peripheral class object, but also automatically has a reference pointing to this peripheral Class Object. Within this scope, the internal class has the right to operate. all members include private members;
Interface Incrementable
{
Void increment ();
}
Class Callee1 implements Incrementable
{
Private int I = 0;
Public void increment ()
{
I ++;
System. out. println (I );
}
}
Class MyIncrement
{
Void increment ()
{
System. out. println ("other increment ");
}
Static void f (MyIncrement mi)
{
Mi. increment ();
}
}
Class Callee2 extends MyIncrement
{
Private int I = 0;
Private void incr ()
{
I ++;
System. out. println (I );
}
Private class Closure implements Incrementable
{
Public void increment ()
{
Incr ();
}
}
Incrementable getCallbackReference ()
{
Return new Closure ();
}
}
Class Caller
{
Private Incrementable callbackRefference;
Caller (Incrementable cbh)
{
CallbackRefference = cbh;
}
Void go ()
{
CallbackRefference. increment ();
}
}
Public class Callbacks
{
Public static void main (String [] args)
{
Callee1 c1 = new Callee1 ();
Callee2 c2 = new Callee2 ();
MyIncrement. f (c2 );
Caller caller1 = new Caller (c1 );
Caller caller2 = new Caller (c2.getCallbackReference ());
Caller1.go ();
Caller1.go ();
Caller2.go ();
Caller2.go ();
}
}
Output
Other increment
1
2
1
2
The Callee2 inherited word MyIncrement and the latter already have a different increment () method and the increment () expected by the Incrementable Interface () the method is completely unrelated. Therefore, if Callee2 inherits MyIncrement, it cannot overwrite the increment () method for the purpose of Incrementable. Therefore, it can implement Incrementable using internal classes independently.
The internal class Closure implements Incrementable 1 to provide a hook that puts Caller2 back and is a secure hook. No matter who gets the reference of this Incrementbale, it can only call increment (). There is no other function.