Javastive_java 2: Use overload functions with caution

Source: Internet
Author: User

The desire to write a technical blog once a week has not been fulfilled. From this week onwards, the blog time is every Friday.


One important feature of OOP is polymorphism. There are multiple ways to achieve polymorphism. For example, overload, overwite rewriting, and interface-oriented programming. However, in practical applications, you should use overload with caution, which is also mentioned in objective Java. The following shows the Code mentioned in eJava:

@ Test
Public void testOverWrite (){
List IntList = new ArrayList ();
Set IntSet = new HashSet ();

For (int I =-3; I <3; I ++ ){
IntList. add (I );
IntSet. add (I );
}
System. out. println (intList + "--->" + intSet );

For (int I = 0; I <3; I ++ ){
IntList. remove (I );
IntSet. remove (I );
}

System. out. println (intList + "###" + intSet );

}

If there is no test, many people may think the output is like this:

[-3,-2,-1, 0, 1, 2] ---> [0, 1, 2,-3,-2,-1]
[-3,-2,-1] ### [-3,-2,-1]

However, the result is as follows:

[-3,-2,-1, 0, 1, 2] ---> [0, 1, 2,-3,-2,-1]
[-2, 0, 2] ### [-3,-2,-1]

The first line is certainly okay, And the intSet is okay. Many people may have questions about intList, ''why is it different from intSet'

In fact, this problem was not solved before JDK 5. JDK 5 and later added the function of automatically encapsulating the box. The basic type and reference type will automatically help you to convert.

In this way, the index is removed when the List is removed, rather than the data in the container you think.

Public E remove (int index ){
RangeCheck (index );


ModCount ++;
E oldValue = elementData (index );


Int numMoved = size-index-1;
If (numMoved> 0)
System. arraycopy (elementData, index + 1, elementData, index,
NumMoved );
ElementData [-- size] = null; // Let gc do its work


Return oldValue;
}

Rather than this function:

Public boolean remove (Object o ){
If (o = null ){
For (int index = 0; index <size; index ++)
If (elementData [index] = null ){
FastRemove (index );
Return true;
}
} Else {
For (int index = 0; index <size; index ++)
If (o. equals (elementData [index]) {
FastRemove (index );
Return true;
}
}
Return false;
}

Jdk automatically unboxing you. HashSet does not have the method to remove the index, so it is called to remove the object.

Public boolean remove (Object o ){
Return map. remove (o) = PRESENT;
}

Therefore, the list issue does not occur.

Therefore, when listing and removing an Integer object, you must note that the result is probably not your desired function.

------------------------- Beautiful split line ------------------

2. When the parameter list is similar, it is best not to use overload. In particular, export public APIs. The most common cause is user confusion. For example, in a public Money class I encountered today, there are two functions with the same parameter list: multiply and multiplyBy, which have the same parameter list. During the first use, I carefully opened the code and remembered that the multiply contains a new object, and the original object value remains unchanged. We also understand that this value cannot be changed. However, the line of code was optimized before the launch, and the 'multiply' was used. During the test, only the half was followed up and the data was correct. The final result is a problem. It is found that multiplyBy is used, and this function changes the original object. A waste of time. Why not write the full name? A function name can contain a maximum of 65535 characters. It seems that complicated service function names cannot be used for such a long time.


-------- Gorgeous split line --------------------

3. Observe the Code:

Private static void printClassName (Set Set ){
System. out. println (set. getClass (). getSimpleName ());
}
Private static void printClassName (List List ){
System. out. println (list. getClass (). getSimpleName ());
}
Private static void printClassName (Collection Col ){
System. out. println ("unknow class name ...");
}
Public static void main (String [] args ){
String [] str = {"a", "B "};
Collection [] Cols = {
New HashSet (),
New ArrayList (),
New HashMap ()
};
For (Collection col: cols ){
PrintClassName (col)
}
}

Overwiter is implemented between parent and child classes, and overload is implemented in the same class. Therefore, overload is determined during the compilation period. Determine the method to call based on the referenced type. So the above three times will print 'unknow class name'. Because the compiler col is of the collection type.

Overload selects a method based on the type of the class instance in which the method is called at run time, So it uses the implementation that is rewritten in the subclass.







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.