Java inheritance easy explained with practical examples

Inheritance is a practical concept in Java, which is an object-oriented programming. It allows programmers to reuse code whenever they need. Inheritance is a fundamental mechanism for building new classes from existing ones

inheritance-color

 

To make the idea of Inheritance clear, we need an example from the real world. Suppose that a company needs information about their employees like their names, ages and salaries. A programmer creates a class Employee with the data they need as shown below:

 

public class Employee {

	String name;
	int age;
	double salary;

	public void printData(){
		System.out.println("name: " + name);
		System.out.println("age: " + age);
		System.out.println("salary: " + salary);
	}
}

 

However, the company have also programmers and database specialists. They need extra information about each one of them. For the programmers and the database specialists they need to know the programming language and the database tool they use.

 

Why Inheritance is used in Java

Many beginner programmers add the attributes programming language and the database tool to the class Employee as shown below. The following class contains redundant information, because not every employee are programmers and database professionals. If you create the object employee for a manager or an administrator, you do not need to know anything about programming languages or database tools. When you even create an object for programmers you do not need to have information about the database tools, because programmers in our example don’t work with database tools.

public class Employee {

	String name;
	int age;
	double salary;
	String language;
	String databaseTool;

	public void printData(){
		System.out.println("name: " + name);
		System.out.println("age: " + age);
		System.out.println("salary: " + salary);
		System.out.println("language: " + language);
		System.out.println("Database Tool: " + databaseTool);
	}
}

 

Another solution is that you create two extra classes for Programmers and Database professionals. For the programmers we add a language attribute and for the database professionals we add a database tool attribute as shown below.

 

public class Programmer {

	String name;
	int age;
	double salary;
	String language;

	public void printData(){
		System.out.println("name: " + name);
		System.out.println("age: " + age);
		System.out.println("salary: " + salary);
		System.out.println("language: " + language);
	}
}

 

The above solution is even worse than the first one, because this time we use the attributes, name, age and salary in two other classes while we have the same in the class employee.  The disadvantage of that kind of programming is that you write a lot of redundant code without taking advantage of reusing what you already have written. Another disadvantage is that writing one method like getName unnecessary several times makes the code difficult to maintain.

 

It might look easy to do it that way in a small program like above, but you have often hundreds classes and thousands lines of code. That could easily generate problems and bugs in the software. Besides, all the methods you write in the class employee, you need to rewrite them in the two other classes apart. That makes maintaining the program difficult. Usually, beginner programmers write many redundant lines of code comparing to advanced developers to achieve the same goal.

 

The UML diagram of the Inheritance “is-a” relationship

In the UML diagram below, the classes programmer and the DatabasePro both extend the Employee class and they inherit the fields name, age and salary from employee. This kind of relationship called the “is-a” relationship, because programmers and Database professionals are also employees in our example.

uml_inheritance_is_a_relationship

The Java code of the UML diagram

Java uses inheritance to allow programmers to reuse the code which are written already in a super class as Employee. Both programmers and database professionals can inherit all the attributes they need from the class Employee, but they need to keep their own special attributes in their own classes. The correct code is that to make the class Employee  a super class for both programmers and database professionals. In that way you inherit all what you need from the parent class Employee and add the fields and methods that are specific for the child classes.

 

Here below we see that the classes Programmer and the DatabasePro use the code super.printData() to access the method printData() in their super class.

 

public class Employee {

	String name;
	int age;
	double salary;

	public void printData(){
		System.out.println("name: " + name);
		System.out.println("age: " + age);
		System.out.println("salary: " + salary);
	}
}

public class Programmer extends Employee {

	String language;

	public void printData(){
		super.printData();
		System.out.println("language: " + language);
	}
}

public class DatabasePro extends Employee {

	String databaseTool;

	public void printData(){
		super.printData();
		System.out.println("Database Tool: " + databaseTool);
	}
}

 

In the above code, the class Employee is a super class or a parent of both classes Programmer as well as DatabasePro. In Java we use the key extends to inherit from a superclass.

In the following code we instantiated the object p which is a programmer and we use p.name, p.age and p.salary which allow the access to those attributes in the class superclass.

 

public class TestEmployee {

	public static void main(String[] args){
		Employee e = new Employee();
		e.name = "Emily";
		e.age = 45;
		e.salary = 65520.00;

		Programmer p = new Programmer();
		p.name = "Ben";
		p.age = 37;
		p.salary = 77435.00;
		p.language = "Java";

		DatabasePro d = new DatabasePro();
		d.name = "Jack";
		d.age = 28;
		d.salary = 45000.00;
		d.databaseTool = "My SQL";

		e.printData();
		p.printData();
		d.printData();
	}
}

 

If we execute the above code, it will write the following to the standard output:

name: Emily
age: 45
salary: 65520.0
name: Ben
age: 37
salary: 77435.0
language: Java
name: Jack
age: 28
salary: 45000.0
Database Tool: My SQL

Super class constructor

When you call a constructor in a subclass, a call is directly made to its super class constructor. See exercise 2!

Exercise 1: Constructors of subclass and superclass.

What happens when the following program is compiled and run?

public class MySuper {

	int b = 1;
}

class MySub extends MySuper {

	int c = 5;

	MySub(int c) {
		System.out.print("-c" + this.c);
	}
	void myMethod(){
		System.out.print("-b" + b);
	}
}

class TestMyProgram {

	public static void main(String[] args){
		MySub mySub = new MySub(4);
		mySub.myMethod();
	}
}

Select the correct answer.


Exercise 2: Subclasses constructor implicitly calls superclass’s no argument constructor

What happens when the following program is compiled and run?

class MySuper {

	int a = 1;

	MySuper() {
		System.out.print("-a" + a);
	}
}

class MySub extends MySuper {

	MySub(int c) {
		System.out.print("-c" + c);
	}
}

class TestInheritance {

	public static void main(String[] args){
		MySub mySub = new MySub(2);
	}
}

Select the correct answer.


Please, leave your questions, feedback and suggestions in the comments below!
SarMaroof.com offers a practical method to learn and improve your Java skills. It avoids unnecessary long boring theoretical explanations, but it uses many exercises and quizzes.


Sar Maroof is graduated from HBO Amsterdam “higher professional education” when he already had a bachelor of science degree in Physics.
He is a SUN certified JSP as well as EJB. He has experience with Java since 2001 and worked for several big as well as small companies and later as a freelancer.
He is the author of Java quizmaster and Build a Java application in 7 days.

Books by Sar Maroof

           
 Subscribe to Sar Maroof's RSS feeds!
 Mail this page to a friend!
 Bookmark this page!
Share on FacebookTweet about this on TwitterShare on RedditShare on LinkedIn

4 Comments

Add a Comment
  1. I adore this website – its so usefull and helpfull.

  2. Your post is valuable , thanks for the info.

  3. Very clear explanation and examples. Thanks for posting this article!

    1. Shoot, so that’s that one suesopps.

Leave a Reply

Your email address will not be published. Required fields are marked *

Sarmaroof © 2017