Quantcast
Channel: None – Dec's Dom Blog
Viewing all articles
Browse latest Browse all 30

Getting To The Java Roots of XPages – Part 13

$
0
0

In todays part I’m going to talk about Extending a class in Java.

The concept is very simple, There is an existing class that does 90% of what you need it to do but your application needs some extra functionality to get it to 100%. If you have access to the code for the original class you could just add some additional methods to it to get that extra 10% but in a lot of cases you may not have that access or maybe you do have the access but that code is on a different update cycle and you need to get your application out the door quicker.

In this case we can create a new java class and tell it to extend the class that has the 90% of the code we need. The new class will inherit all of the methods of the extended class and then we can add our own methods as required.

Lets take a look at the following example

package scary.java.demo;

public class StaffInfoPlus extends StaffInfo {

    private static final long serialVersionUID = 1L;
    private String reversedName;
    
    public StaffInfoPlus() {
	
    }

    public String getReversedName() {
	if (reversedName == null) {
	    reversedName = getLastName() + " " + getFirstName();
 	}
        return reversedName;
    }

}

I’m creating a new class called StaffInfoPlus and I’m telling it to extend the previous class that we worked on called StaffInfo. In this class I’ve added one method called getReversedName which is very simply taking the person’s last name and first name and putting them into a simple string with a space between them and returning the value.

But where is it getting the last name and first name and how does it know what person we are dealing with? That is the beauty of extending a class. Our new class StaffInfoPlus has all the methods that StaffInfo has so I can call staffInfoPlus.load(employeename) and while the method doesn’t directly exist in StaffInfoPlus it does exist in StaffInfo and it will be run and all the variables loaded just like before. If I call StaffinfoPlus.getFirstName() then I’ll get the loaded employees first name. Therefore the calls to getlastName() and getFirstname() in the getReversedName() method are just calling those methods in StaffInfoPlus but because they don’t exist directly in that class they are really calling them the extended StaffInfo class.


Viewing all articles
Browse latest Browse all 30

Trending Articles