Java override method rewrite learning notes

Source: Internet
Author: User

The following is a summary of some learning notes about java override method rewriting. The following is a record of some help for those who need to learn.

Overload indicates that multiple methods with the same name can exist in the same class, but the parameter lists of these methods are different (that is, the number or type of parameters are different ). If the parameter lists of the two methods are the same, can we make them return different values for overloading? The result is not acceptable ., We can use the reverse Identification Method to illustrate this problem, because sometimes we can call a method without defining the returned result variable, that is, do not care about the returned result. For example, we call map. in the remove (key) method, although the remove method has a return value, we usually do not define variables that receive the returned results. In this case, assume that there are two methods with the same name and parameter list in this class, java cannot determine which method the programmer wants to call because it cannot determine the type of the returned result.
Override indicates that the method in the subclass can have the same name and parameter as a method in the parent class. When this method is called through the instance object created by the subclass, the definition method in the subclass is called, this is equivalent to overwriting the exactly same method defined in the parent class, which is also a manifestation of object-oriented programming polymorphism. When a subclass overwrites the method of the parent class, it can only throw fewer exceptions than the parent class, or throw the child exception thrown by the parent class, because the subclass can solve some problems of the parent class, there cannot be more problems than the parent class. The access permission of the subclass method can only be larger than that of the parent class, and cannot be smaller. If the method of the parent class is of the private type, there is no overwrite restriction on the subclass, which is equivalent to adding a new method to the subclass.


The trap of rewriting (Override) API methods

During writing Java applications, we often need to extend the classes in the API and rewrite the functions in the API. However, unexpected problems may also occur in this process. You need to confirm whether the method you override this parent class will have a negative impact.

For example, I recently encountered an interesting question in SOSO. When I set the background color of a JPanel component while using Swing, I found that the background color has not changed. The Code is as follows:

The Code is as follows: Copy code


Package com. lvjava;

Import java. awt .*;
Import javax. swing .*;

Public class BackgroundTest {
Public static void main (String [] args ){
New KFrame ();
}
}

Class KFrame extends JFrame {
KFrame (){
Setdefaclocloseoperation (JFrame. EXIT_ON_CLOSE );
SetSize (500,500 );
SetVisible (true );
JPanel component = new KComponent ();
Add (component );
Component. setBackground (Color. YELLOW );
}
}

Class KComponent extends JPanel {
Public void paintComponent (Graphics g ){
G. drawString ("King's", 150,150 );
}
}

This Code seems to be okay. It is strange when running component. setBackground (Color. YELLOW); this statement does not work.
The problem is that the paintComponent method is rewritten when the KComponent object inherits JPanel, because the background color is drawn in the paintComponent () method. The original author has rewritten this method, therefore, this method in the parent class is no longer executed, and the author does not add a method to draw the background color. When running, only the drawing text King's is displayed, instead of making any changes to the background color. If we directly change KComponent to the following code, we can solve this problem by calling the method of the parent class and executing the required part:

The Code is as follows: Copy code

Class KComponent extends JPanel {
Public void paintComponent (Graphics g ){
Super. paintComponent (g );
G. drawString ("King's", 150,150 );
}
}

In fact, a better modification method is to remove KComponent and directly use the JLabel component to display the "King's" text, instead of rewriting the parent class API.
When rewriting methods in unfamiliar APIs, we must be cautious about whether such problems exist, when I develop interface programs such as RCP that need to override the parent class method, I will carefully check whether there are uncancelable actions in the parent class API, if yes, you need to handle the rewrite process with caution, because once such a problem occurs Debug, it is difficult to find the cause of the problem.

For example, in RCP projects, we often extend the titleareadised component to implement our own dialog box. Generally, we need to override the buttonPressed method to process events such as dialog box submission or Refresh. There are similar problems here. Let's first look at the code of this method in the parent class API:

 

The Code is as follows: Copy code
Protected void buttonPressed (int buttonId ){
If (IDialogConstants. OK _ID = buttonId ){
OkPressed ();
} Else if (IDialogConstants. CANCEL_ID = buttonId ){
CancelPressed ();
}
}

Obviously, the default buttonPressed method only checks OK _ID and CANCEL_ID. If it is CANCEL_ID, The cancelPressed method is executed to close the dialog box. If it is OK _ID, the default okPress () is empty.

At this time, if you can choose to override the okPress method to achieve this purpose, rather than override buttonPressed, But if you customize the Button ID, you must override the buttonPressed method, you need to note that at the end of the rewrite method, you must call super. buttonPressed (buttonId) uses the method of the parent class to handle the event of clicking the CANCEL_ID button. Otherwise, you will find that the Cancel button has lost its original role, and you have to implement this process manually, even if you implement this process, such code may have potential risks. Therefore, we should be careful when rewriting the parent class API.

The Code is as follows: Copy code

@ Override
Protected void buttonPressed (int buttonId ){
// TODO Auto-generated method stub
If (buttonId = IDialogConstants. OK _ID ){
If (CaptionUtil. isEmpty (usernameText. getText ())){
This. setErrorMessage ("the user name cannot be blank ");
UsernameText. setFocus ();
Return;
}
If (! CheckLogonAtDb (usernameText. getText (), passwordText. getText ())){
Return;
}
} Else {
Super. buttonPressed (buttonId );
}
}


To sum up

1. the method in the subclass has the same return type as the method in the parent class.
2. the method in the subclass has the same name as the method in the parent class.
3. the method in the subclass has the same parameter list as the method in the parent class.
4. The access level of the method in the subclass cannot be lower than the access level of the method in the parent class (for example, if the parent class method level is protected, then the subclass overrides this method, the level must be protected or public, which must be the same or wider as the access level of the parent class; otherwise, compilation fails)
5. The range of exceptions thrown by the subclass method cannot be greater than the range of exceptions thrown by the method in the parent class. This principle is also true if the subclass does not throw an exception, that is, the parent class throws an exception, the subclass does not throw an exception and compilation is successful .)

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.