Import java. io .*;
Import java. util .*;
Class Why {
Public static void main (String [] args ){
Vector v = new Vector (3, 2 );
V. addElement ("");
V. addElement ("B ");
V. addElement ("c ");
Enumeration e = v. elements ();
While (e. hasMoreElements ()){
...
}
}
As we all know, Enumeration is an interface that defines two methods, hasMoreElements () and nextElement (). Since it is an interface, there must be no "Implementation Details" (the introduction of the interface technology is probably related to this). However, in the above program, Vector. the elements () method returns an Enumeration object. Here, I am confused. When the above program generates the Object e of this interface, it calls e. hasMoreElements () method. Since e is an object of the Enumeration interface with "no implementation details", the class actually implements this interface, what about "Implementation Details? Even if one or more "classes" exists, how does the JVM know in the above program that e here is "Huludao ", what exactly is the "detail" of the "Implementation class" running?
I think, if I understand this problem, the answer to the question "interface implementation Java 'hide implementation details'" will be solved.
Answer:
Check src of java. util. vector. The source code of the elements () method is as follows:
Public Enumeration elements (){
Return new Enumeration (){
Int count = 0;
Public boolean hasMoreElements (){
Return count <elementCount;
}
Public Object nextElement (){
Synchronized (Vector. this ){
If (count <elementCount ){
Return elementData [count ++];
}
}
Throw new NoSuchElementException ("Vector Enumeration ");
}
};
}
Is this an inner class )?
---------------------------------
Public Enumeration elements () {This method has an anonymous internal class,
Methods In the Enumeration interface have been implemented in the anonymous internal class,
E. hasMoreElements () calls methods implemented by anonymous internal classes, so users do not need
To understand the implementation details in elements (), you only need to know the methods in the Enumeration interface.
Therefore, the Enumeration interface achieves the goal of hiding implementation details.