View RSS Feed

My Java Tips

Inheritance by example

Rate this Entry
by , 11-09-2011 at 05:53 PM (1257 Views)
I have fond many developers who very seldom use inheritance while coding in Java. The reason they give is why one should make code difficult to understand? I am amazed at this reason because Java inheritance is similar to natural inheritance.


Lets fist understand the basics.

Mazda is a Car > Mazda inherits Car
Java is a programming language > Java inherits Prog. Language
Australia is a country > Australia inherits Country

Whenever you have IS A relation between two entities, you can use inheritance. Basic idea is to use the attributes and methods of parent class (super class) in the child class (base class).

Lets take an example:

We have a class called Car that has few attributes, getter/setter methods and some other methods that are generic to cars.

Java Code:
public class Car {

	private String carNo;
	private String color;
	private String engine;
	public String getCarNo() {
		return carNo;
	}
	public void setCarNo(String carNo) {
		this.carNo = carNo;
	}
	public String getColor() {
		return color;
	}
	public void setColor(String color) {
		this.color = color;
	}
	public String getEngine() {
		return engine;
	}
	public void setEngine(String engine) {
		this.engine = engine;
	}

	public void startCar()
	{
		System.out.println("Car class - Car started");
	}

	public void stopCar()
	{
		System.out.println("Car class - Car stopped");
	}

}

Now, we will write a class called Mazda that will inherit from class Car.


public class Mazda extends Car {

private String model;

public void turnOnSpecialFeatures()
{
System.out.println("Mazda class - Special features are now running.");
}

public String getModel() {
	return model;
}

public void setModel(String model) {
	this.model = model;
}

}
Now all the public members of Car class are visible in Mazda class. Now lets make this example meaningful. We will write another class that will create object of class Mazda and will set data using the setter methods. We also will call to other declared methods.

Java Code:
public class MainClass {

	public static void main(String[] args) {
		Mazda obj = new Mazda();
		obj.setCarNo("AUS1234");
		obj.setColor("White");
		obj.setEngine("200CC");
		obj.setModel("Mazda.626");

		obj.startCar();
		obj.turnOnSpecialFeatures();
		obj.stopCar();

	}

}
obj is an object of class Mazda but we can access public methods defined in class Car because Mazda class is inheriting from Car class.

Output:


Car class - Car started
Mazda class - Special features are now running.
Car class - Car stopped

Submit "Inheritance by example" to Facebook Submit "Inheritance by example" to Digg Submit "Inheritance by example" to del.icio.us Submit "Inheritance by example" to StumbleUpon Submit "Inheritance by example" to Google

Tags: None Add / Edit Tags
Categories
Java SE

Comments