Adding additional methods to an existing class by extending it is not the only thing that you can do with Extends. You can also override existing methods in the extended class. In our StaffInfo class the getInternetAddress will return a simple internet email address like jbloggs@somecorp.xyz but for your application you need it to look like ‘Joe Bloggs
Now you COULD create a new method just like the getReversedName() method in the last part but then you would have to go back to the application and change all the calls to getInternetAddress() to your new method name. Instead, however, you can create your own getInternetAddress() method in StaffInfoPlus.
@Override public String getInternetAddress() { return getCommonName() + " <" + super.getInternetAddress() + ">"; }
The @Override is called a compiler annotation. It is not strictly needed and the above would work perfectly without it but it does help the compiler to know that we are overriding a method in the extended class ( and an warning will show if it comes to an @Override on a method that doesn’t exist in the extended class ).
After the annotation is our new version of the getInternetAddress() method. It is returning a string made up of the users common name, a space, an opening angle bracket, the users internet address and then a closing angle bracket.
Look closely at how we get the users internet address. I’m overriding the getInternetAddress() method but I also need to get the users internet address. To do this I use a special keyword called ‘super’. This tells the compiler that I want to call the version of this method in the class that I’m extending and not the version in this class.
So my StaffInfoPlus class has all the methods that exist in the StaffInfo class, plus my reversedName method and now, any call to getInternetAddress() will use the version in this class rather then the StaffInfo class that I’m extending.
This java stuff is not so scary after all…