Question

What does the 'extends' keyword mean?

Answer

Java, like other object-orientated languages, supports class inheritance. Inheritance allows one class to "inherit" the properties of another class. For example, all Java objects are inherited from the java.lang.Object class. This means that we can call the toString() method inherited from java.lang.Object, and get a string representation of any java object, such as an Integer, a Float, a Double, etc.

Take a look at the following example, which demonstrates the use of the 'extends' keyword.

public class A extends java.lang.Object {
	public int number;

	public String toString() {
		return new String("Value : " + number);
	}
}

In this example, we implicitly state that we extend java.lang.Object, and override the functionality of the toString() method by providing our own function. Note that all classes, whether they state so or not, will be inherit from java.lang.Object.

Our next example shows a more common use of the keyword 'extends'. In this example, we inherit from class A, which means that B will also contain a field called number, and a function called toString().

public class B extends A {
	public void increment() {
		number++;
	}
}

public class ABDemo {

	public static void main (String args[]) {
		// Create an instance of B
		B counter = new B();

		// Increment B
		counter.increment();

		// Call toString() method
		System.out.println ( counter.toString() );
	}
}

Even though we never defined a toString() method, or added a number field to the B class, it has inherited this information from A. This is a powerful feature of object-orientated programming, and can save significant time when developing classes.


Back