You are on page 1of 4
7 ‘ You Do It Overriding a Superclass Method In the previous “You Do It’ section, you created Party and DinnerParty classes. The DinnerParty class extends Party, and so can use its displayInvitation() method. Suppose that you want a DinnerParty object to use a specialized invitation. In this section, you override the parent class method so that the same method name acts uniquely for the child class object. 1. 2. Open the DinnerParty java class. Change the class name to DinnerParty2, and save the file as DinnerParty2.java. Create a displayInvitation© method that overrides the parent class method with the same name as follows: Override public void displayInvitation) { System.out.printIn("Please come to my dinner party! ¥ Save the class and compile it. Open the UseDinnerParty java file. Change the class name to UseDinnerParty2, and immediately save the file as UseDinnerParty2.java. (continues) (continued) Change the declaration of the abinnerParty object so that it uses the DinnerParty2 Class as a data type and DinnerParty2 as the constructor name, Save the class, compile it, and execute it. Figure 10-7 shows a typical execution. Each type of object uses its own version of the displayInvitation() method. oer eer eae eee tea eae Ree an erie Figure 10-7 Typical execution of the UseDinnerParty2 program Purposely introduce an error into the child class di splayInvitation() method header. For example, you might make the 1 lowercase, as in displayinvitationO. Save and compile the DinnerParty2.java file. You receive a compiler error message similar to the following: ‘Method does not override or implement a method from a supertype. (You will learn about the keyword implements in Chapter 11.) Comment out the eoverrde annotation by inserting two forward slashes ( //) in front of it. Save and compile the DinnerParty2.java fle. This time the compilation is successful because displayinvitation() is a valid method name—it's just not one that overrides a parent class method. ff you wanted to use this method in an application, you would have to remember to use a lowercase i for invitation in the method name. However, it would not be recommended because you could easily confuse displayinvitationO with displayInvitation(). Remove the comment slashes from the @override annotation and reinstate the uppercase T in the displayinvitation() method header. Save and recompile the class, and confirm itis errorfree.

You might also like