Lesson 9 – Inheritance in Java

Inheritance in Java is similar to real-life inheritance. In real life, a child can inherit parents characteristics. In the same way, in Java inheritance, a class can inherit public or protected member variables and methods from another class. A class that inherits another class is called derived class or child class whereas a class that is inherited by another class is called a parent class or base class. In Java, a child class cannot inherit multiple parent classes. On the other hand, a parent class can be inherited by multiple child classes.

A Simple Inheritance Example

Let’s see how to extend one class from another:

class User{

public String name;
public String password;

public void login()
{
System.out.println("Welcome "+ name);

}
}

class Man extends User{
public String email;
public void print_email()
{
System.out.println("Your email is: "+ email);

}

}

To inherit from another class the keyword “extend” is used in Java. In the code above we defined a class “Man” that inherits from “User” class. This means that the “Man” class inherits the member variables “name” and “password” and the method “login” from the “User” class. In addition the “Man” class also contain a variable “email” and a method “print_email” which prints the email. Let’s now create object of the “Man” class and see how it accesses the parent class members.

Welcome mike
Your email is: abc@xyz.com

Passing Values to Parent Class Constructor

You can also pass values to parent class constructor from a child. Inside the child class constructor, you have to use the “super” keyword and pass the values for parent class constructor in the pair of parenthesis that follows the “super” keyword as shown below:

class User{

public String name;
public String password;

public User(String name, String password)
{
this.name = name;
this.password = password;
}

public void login()
{
System.out.println("Welcome "+ name);

}
}

class Man extends User{
public String email;
public Man(String name, String password, String email)
{
super(name, password);
this.email = email;
}
public void print_email()
{
System.out.println("Your email is: "+ email);

}

}

Let’s now create object of the “Man” class that calls the parent class constructor:

public class MainClass {

public static void main(String[] args) {
// TODO Auto-generated method stub

Man m = new Man("mike", "abcd", "abc@xyz.com" );
m.login();
m.print_email();
}
}

The output of the above code is as follows:

Welcome mike
Your email is: abc@xyz.com

What’s Next?

In this lesson, you explored inheritance, in the next and final lesson of the introductory course, we will introduce you to exception handling in Java.