Archive for Java

Java Simple Inheritance

Tuesday, May 17th, 2011

By: Jatin Chawla

Simple Inheritance means heredity from one generation to second; A child inherit many good and bad qualities from his parents such as some identification marks, diseases etc. If we talk about Java Simple Inheritance, there are only one base and derived class. We can define this as a pictorial representation as:

We show a picture as an example of Simple Inheritance

public class square {

	int length, breadth;
	public void get(int x, int y)
	{
		length=x;
		breadth=y;
	}
	int area()
	{
		return(length*breadth);
	}

}

 

public class cube extends square
{
	int height;
	public void getdata(int x,int y,int z)
	{
		get(x,y);
		height=z;
	}
	int volume()
	{
		return(length*breadth*height);
	}

}
public class RunInheritance {
	public static void main(String a[])
	{
		cube C=new cube();
		C.getdata(10,20,30);

		int b1=C.area();
		System.out.println("Area of Square: "+b1);

		int b2=C.volume();
		System.out.println("Volume of Cube: "+b2);
	}

}

Output

Area of Square: 200
Volume of Cube: 6000

In above example, it is defined that every square has a fixed area and volume; We create two classes i.e. Square and Cube, In first class we define the area of square and in next / derived class we defined the volume of Cube. We can access the area and volume of the Square or Cube by calling the function through Cube class object. As we know that A single Cube has 6 faces of squares that have equal length, breadth and height; In our example, It is shown that A cube can carry 6 square and then it formed in “Cube”. We have just used the functionality of super class (Square Class) in Sub Class (Cube Class).

There are many more examples of Simple Inheritance.

  • 1. A student is always a person i.e. A student will contain all attributes and behaviors / features of person class.
  • 2. A car is counted in four wheelers so A car will contain about all general features of Four wheelers.
  • 3. A multimedia mobile is considered as a simple mobile i.e. a multimedia mobile will adopt all features of General mobile.