Home > Articles > Programming > Java

  • Print
  • + Share This
This chapter is from the book

Changing References to Use a Supertype

You can use the Use Supertype Where Possible refactoring command to change code to reference objects of a superclass (or other type) instead of objects of a subclass. The operation only changes the reference in places where your code can accommodate such upcasting.

Typically you would use this refactoring operation to enable a single method to take as an argument different types of objects (all deriving from the same superclass).

This operation might be particularly useful after you have used the Extract Superclass command.

To change references to a supertype:

  1. Select the class to which you want to replaces references and choose Refactor | Use Supertype Where Possible.
  2. In the Select Supertype to Use list, select the class or other type that should be referenced instead of the type currently referenced and click Next.

    If you have deselected the Preview All Changes checkbox, the changes are applied immediately.

    If you leave the Preview All Changes checkbox selected, the Refactoring window appears with a preview of the changes.

  3. In the Refactoring window, look at the preview of the code to be changed. If there is a modification that you do not want to be made, deselect the checkbox next to the line for that change.
  4. Click Do Refactoring.

    If you later find that the refactoring has had some consequences that you would like to reverse, you can choose Refactor | Undo.

  • + Share This
  • 🔖 Save To Your Account