View RSS Feed

Java Object

Composition Syntax for Reuse

Rate this Entry
by , 11-29-2011 at 05:21 PM (2973 Views)
One of the best features of Java is code reuse. But like any tool, it needs to be used effectively. Most programmers might be lead to think that when I talk of reuse only relates to extending a class. Now there is nothing wrong with reusing a class by extending it or using it directly. This type of reuse is using the class without the risk changing the existing code. First we can create objects of the existing class inside the new class. We call this composition. It is a new class composed of objects of existing classes. What you’re doing is reusing the functionality not its form. The second approach is to create a new type of class from an existing class. You take the form of an existing class and add code to it without making changes to the existing class (inheritance).

An example of composition below.

Java Code:
public class Transport {
	public void move(){
	}
	
	public void start(){	
	}
	
	public void stop(){	
	}
}


public class Airplane {

	private Transport transport;

	public Airplane() {
		transport = new Transport();
	}

}

Here is the same example shown as inheritance

Java Code:
public class Airplane extends Transport {

}

Submit "Composition Syntax for Reuse" to Facebook Submit "Composition Syntax for Reuse" to Digg Submit "Composition Syntax for Reuse" to del.icio.us Submit "Composition Syntax for Reuse" to StumbleUpon Submit "Composition Syntax for Reuse" to Google

Comments