Java bomb: overloading, rewriting, hiding, masking, and masking (1)

Source: Internet
Author: User

See the "encapsulated set Encapsulate Collection" section in "refactoring comments version)". This refactoring method has different processing methods for different Java versions, so the annotator gave a prompt: The new Collections API in Java 2 is mainly developed and improved by the authors of the two books "Java" and "valid Java. I think this is really a big news. The books written by developers of Java class libraries must be read. Developers must have thoroughly explored the internal mechanism of Java and may be able to obtain unknown knowledge points from the book.

Fortunately, I remember that I downloaded a clear electronic version of "Java confusing Chinese version" on my computer, so I changed the course and started reading this book. I really don't know. I was shocked! There are 95 Java puzzles in it. After reading them a little bit, I am both ashamed and excited, because the questions inside are really "inexplicable". The straightforward point is: I can't even think of it... To really master Java, I think Java cannot be confused. Most of the puzzles are never seen before.

 

As shown in the title of the article, I seem to have come to understand several terms in "Java puzzles". The reason why I used them seems to be modified is that I have been involved in heavy loading, rewriting, and hiding, while masking and masking may have been seen but forgotten. Let's sort out some Java puzzles related to this article and describe them with your own understanding.

Overload ):The relationship between multiple methods with the same name but different parameter lists in the same class.

We are familiar with heavy load. The most common one is to use it in multiple constructors of the class. Let's take a look at the Java help documentation to understand this situation. In Java, the author gives the following puzzle:

 
 
  1. public class Confusing {   
  2.       
  3.     private Confusing(Object o) {   
  4.         System.out.println("Object");   
  5.     }   
  6.       
  7.     private Confusing(double[] dArray) {   
  8.         System.out.println("double array");   
  9.     }   
  10.       
  11.     public static void main(String[] args) {   
  12.         new Confusing(null);   
  13.     }   
  14. }  

What will be output in main? At the first day of the year, there was no much analysis and I thought it should be the output "Object". Although the array in Java is actually a reference type, after all, the Object is the final parent class of all classes, at present, even the basic data type variables in JDK parameters can be automatically converted into a packaging class and become the Object subclass. So I thought conservatively that the null parameter should match the overload method of the Object.

However, the answer is wrong. The JVM resolves the overloaded method like this: first, find all possible methods that match the method name; then, filter out the possible overload methods based on the passed parameters. Finally, matchMost accurate. Therefore, the puzzle above becomes to determine which one is the most accurate.

There is a mechanism for determining how to be most accurate: if an overload method can receive all the real parameter types passed to another overload method, for the parameter list, obviously, the latter is at least a subset of the former, and of course it is more accurate.

Back to the puzzle, Confusing (Object) can accept any parameter passed to Confusing (double []). Any array reference can eventually be an Object), so main () the null in should be matched to Confusing (double []) by JVM, and the output is opposite to what I think.

Summary:This puzzle shows that when writing a heavy load method, it is best to clearly distinguish the parameter lists in each method, so that there is no mutual inclusion or ambiguous relationship between them. Although the overload is to pass in real parameters in the method with the same name, the dynamic parsing of JVM selects the appropriate method, but sometimes it is easy to fall into the mines behind this convenience. One feasible method is to provide different method names. But the name of the constructor must be the same?

In fact, in Chapter 6 of "Reconstruction and mode", the author uses his project experience to explain the topic "creation", even if it is a constructor, there are also good refactoring techniques to separate their clear regions, instead of using heavy loads, but using different names, delegate the constructors to the private constructors with the largest and complete parameter list. It's also a classic, worth reading...

 

Override ):In the parent classInstance methodImplemented by its subclass. Since it is an instance method, it is not static modified, otherwise it is a static method, it is calledClass Method. In my opinion, it is the existence of rewriting this mechanism that provides the foundation for the polymorphism mechanism. The Methods declared in an interface can also be rewritten, because part of the interface is also for polymorphism.

For rewriting, the following puzzles are found in Java:You cannot call methods that may be overwritten by the quilt class in the constructor.

 
 
  1. class Point {  
  2.     protected final int x, y;  
  3.     private final String name;  
  4.       
  5.     Point(int x, int y) {  
  6.         this.x = x;  
  7.         this.y = y;  
  8.         name = makeName();  
  9.     }  
  10.  
  11.     protected String makeName() {  
  12.         return "[" + x + "," + y + "]";  
  13.     }  
  14.       
  15.     public final String toString() {  
  16.         return name;  
  17.     }  
  18. }  
  19.  
  20. public class ColorPoint extends Point {  
  21.     private final String color;  
  22.       
  23.     ColorPoint(int x, int y, String color) {  
  24.         super(x, y);  
  25.         this.color = color;  
  26.     }  
  27.       
  28.     protected String makeName() {  
  29.        return super.makeName() + ":" + color;  
  30.     }  
  31.       
  32.     public static void main(String[] args) {  
  33.         System.out.println(new ColorPoint(4, 2, "purple"));  
  34.     }  

The program running result is not []: purple, but []: null. Why? Let's take a look at the code that has been annotated with the process label below.

 
 
  1. Class Point {
  2. Protected final int x, y;
  3. Private final String name;
  4.  
  5. Point (int x, int y ){
  6. This. x = x;
  7. This. y = y;
  8. Name = makeName (); // 3. The makeName () is overwritten by the quilt class ()
  9. }
  10.  
  11. Protected String makeName (){
  12. Return "[" + x + "," + y + "]";
  13. }
  14. Public final String toString (){
  15. Return name;
  16. }
  17. }
  18.  
  19. Public class ColorPoint extends Point {
  20. Private final String color;
  21.  
  22. ColorPoint (int x, int y, String color ){
  23. Super (x, y); // 2. Call the Point parent class Constructor
  24. This. color = color; // 5. initialize the color, but it is too late...
  25. }
  26.  
  27. Protected String makeName (){
  28. // 4. The problem is that it was called before the subclass constructor.
  29. // At this time, the color is null !!!
  30. Return super. makeName () + ":" + color;
  31. }
  32.  
  33. Public static void main (String [] args ){
  34. // 1. Call the constructor of the ColorPoint subclass.
  35. System. out. println (new ColorPoint (4, 2, "purple "));
  36. }
  37. }

The idea is clear. In the constructor of the ColorPoint subclass, this. color = color; null is taken as the value of String color before being executed. It is precisely because this kind of back-to-back call makes the program abnormal. In my opinion, it is similar to "Callback.

To remove the unreasonable code structure, you 'd better remove the makeName () method called in the Point parent class constructor, and then judge and call makeName () in toString () for name initialization, as follows:

Summary:Rewriting is important for polymorphism, but if an incorrect code structure is designed, the originally desired polymorphism will be distorted or even lead to reverse effects. Therefore, do not call methods that may be overwritten in constructors.

 

It seems that there are too many articles with too many texts that are easy to make people dizzy. I wrote two words in a vague manner. Let's write them separately. As a matter of fact, I read some "Java puzzles" to understand that there are many points of attention in Java. It is difficult to identify grammar and mechanism knowledge points when appropriate!

I remember reading a piece of lyrical prose in the high school Chinese class titled "oh-xiangxue !" I read "Java puzzles" and want to say "Oh -- Java !"~~~~ (& Gt ;_& lt ;)~~~~

Summary:

1. In our programming field, a good book is really just a hit, and we can see that we have no time or strategy to absorb it;

2. Sometimes, when reading a good book, pay attention to the "friendship links" of the author for other books or related books recommended by the publishing house. This frees you from slowly searching for a good book, O (partition _ partition) O ha!

This article is from the "ant" blog, please be sure to keep this source http://haolloyin.blog.51cto.com/1177454/372691

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.