Inheritance in Java

Inheritance is the way through which a class acquires all the properties and members of other class. Inheritance represents the IS-A relationship.

The class acquiring the properties is called child class and the class from which properties are acquired is called parent class. We make use of ‘extends‘ keyword for inheritance.

With inheritance the child class object can access the members of parent class.

class Daughter extends Mother

Java supports following types of inheritance :-

  1. Single level inheritance
  2. Multilevel inheritance
  3. Hierarchical inheritance
  4. Multiple inheritance (Only in case of Interfaces)

Let us look at an example to understand inheritance :

public class Tech4Humans {
	public static void main(String[] args) {
		Daughter daughter1 = new Daughter();

		// we are able to access instance variable of Mother class with Daughter object due to inheritance
		daughter1.eyeColor = "Blue";
		daughter1.education = "Engineer";

		// we are able to access method of Mother class with Daughter object due to inheritance
		daughter1.getEyeColor();
		daughter1.getEducation();
	}

}

class Mother {
	String eyeColor;

	void getEyeColor() {
		System.out.println("Eye color is " + eyeColor);
	}
}

//'extends' keyword is used for inheritance
class Daughter extends Mother {
	String education;

	void getEducation() {
		System.out.println("Education qualification is " + education);
	}
}

Output

Eye color is Blue
Education qualification is Engineer

In the above code the instance variables and methods of Mother class are inherited to Daughter class, that is why Daughter class object is able to access the Mother class members.

Important points about Inheritance :

  1. Constructors are not inherited but when we create an object of child class then parent class constructor is also called.
  2. static‘ members of parent class are inherited to child class.
  3. private‘ members are not inherited.
  4. If both parent and child class has same variable name initialized then child class object will take the value of variable initialized in child class.
  5. If both child and parent class has same method name but different signature then it is called overloading.
  6. If both child and parent class has same method name and same signature then it is called overriding.
  7. super‘ keyword is used to access members of parent class from child class directly.

Let us now take a look at Single Level Inheritance.

Leave a Comment