19) Inheritance (is-a relationship)

What is inheritance?

Real life example:

All living beings inherit the characteristics and behaviors of their parents. The off- spring of a fly looks and behaves like a fly, and that of a lion looks and behaves like a lion. But despite being similar to their parents, all offspring are also different and unique in their own ways. In addition, a single action may have different meanings for different beings. For example, the action “eat” has different meanings for a fly than a lion. A fly eats nectar, whereas a lion eats an antelope.

In Java

The concept of inheriting characteristics and behaviors from parents can be compared to classes inheriting variables and methods from a parent class. Being different and unique in one’s own way is similar to how a class can both inherit from a parent and define additional variables and methods. Sin- gle actions having different meanings can be compared to polymorphism in Java.

Why we need inheritance?

Example :

Imagine the positions Programmer and Manager within an organization. Both of these positions have a common set of properties, including name, address, and phone num- ber. These positions also have different properties. A Programmer may be concerned with a project’s programming languages, whereas a Manager may be concerned with project status reports.:

Put them in a separate class : 'Employee'

Important Terms:

  • – Superclass—A base class is also known as a superclass.

  • – Parent class—A base class is also known as a parent class.

    • Base class —A class inherited by another class. The class Employee is a base class for the classes Programmer and Manager in the previous examples.

  • Derived class—A class that inherits from another class. The classes Programmer and Manager are derived classes in the previous examples.

    • – Subclass—A derived class is also known as a subclass.

    • – Extended class—A derived class is also known as an extended class.

    • – Child class—A derived class is also known as a child class.

  • IS-A relationship—A relationship shared by base and derived classes. In the previ-

    ous examples, a Programmer IS-A Employee. A Manager IS-A Employee. Because a derived class represents a specialized type of a base class, a derived class IS-A kind of base class.

  • extends—The keyword used by a class to inherit another class and by an inter- face to inherit another interface.

  • implements—The keyword used by a class to implement an interface (inter- faces are covered in the next section).

Benefits :

1) Less code redundancy:

2) Ease of Modification:

Suppose as per some requirement we have to add facebook id

3) Extensibility:

Code that works with the base class in a hierarchy tree can work with all classes that are added using inheritance later.

Assume that an organization needs to send out invitations to all its employees and that it uses the following method to do so:

Because the method sendInvitation accepts an argument of type Employee, you can also pass to it a subclass of Employee. Essentially, this design means that you can use the previous method with a class defined later that has Employee as its base class. Inheritance makes code extensible.

Rules to inherit class members:

A derived class inherits base class members with the following accessibility levels:

    • Default—Members with default access can be accessed in a derived class only if the base and derived classes reside in the same package.

    • protected—Members with protected access are accessible to all the derived classes, regardless of the packages in which the base and derived classes are defined.

    • public—Members with public access are visible to all other classes.

A derived class doesn’t inherit the following members:

    • private members of the base class.

    • Base class members with default access, if the base class and derived classes exist

      in separate packages.

    • Constructors of the base class. A derived class can call a base class’s construc-

      tors, but it doesn’t inherit them (section 6.5 discusses how a derived class can call a base class’s constructors using the implicit reference super).

A class can't extend multiple classes:

Reason:

How to use inheritance in Java

To Achieve inheritance between classes, we should use extends keyword.

Note: Only non-static members of a class will be involved in Inheritance.

Syntax:

class derived-class extends base-class

{

//methods and data members

}

Simple example of Inheritance

package com.gs.ilp.corejava.inheritance;

class Parent {
	public void show() {
		System.out.println("Parent method");
	}
}

public class Child extends Parent {
	public void display() {
		System.out.println("Child method");
	}

	public static void main(String[] args) {
		Child cobj = new Child();
		cobj.display(); // method of Child class
		cobj.show(); // method of Parent class
	}
}

Output

Child method

Parent method

Types of Inheritance

  1. Single Inheritance

  2. Multilevel Inheritance

  3. Hierarchical Inheritance

NOTE: Multiple inheritance is not supported in java

Example:

Single Level inheritance:

package com.gs.ilp.corejava.inheritance;

class A {
	int a = 10;

	void test1() {
		System.out.println("Running test1");
	}
}

class B extends A {
	double d = 10.5;

	void demo1() {
		System.out.println("Running demo1");
	}
}

class SingleInheritance {
	public static void main(String[] args) {
	}
}

Example:

Multilevel Inheritance:

package com.gs.ilp.corejava.inheritance;

class Sample1 {
	void test1() {
		System.out.println("Running Test1");
	}
}

class Sample2 extends Sample1 {
	void test2() {
		System.out.println("Running Test2");
	}
}

class Sample3 extends Sample2 {
	void test3() {
		System.out.println("Running Test3");
	}
}

public class MultiLevelInheritence {
	public static void main(String[] args) {
		System.out.println("Main Starts");
		Sample3 rv1 = new Sample3();
		rv1.test1();
		rv1.test2();
		rv1.test3();
		System.out.println();
		Sample2 rv2 = new Sample2();
		rv2.test1();
		rv2.test2();
		System.out.println("Main Ends");
	}
}

Output:

Main Starts

Running Test1

Running Test2

Running Test3

Running Test1

Running Test2

Main Ends

Why multiple inheritance is not supported in Java

To remove ambiguity. To provide more maintainable and clear design.

Important Points:

  • All public variables of Super class will be inherited by subclass.

  • All default variables will be inherited by all subclasses in the same package only. Subclasses outside the package will not inherit any default member.

  • Private members cannot be inherited by subclass because they will not be visible to the subclass and hence the subclass can create the Method or property with the same name without any problem.

  • Protected variables will be inherited by all subclasses in the same package or outside package (Different from default).

  • Methods which are not inherited cannot be overridden. And hence overridden rules cannot be applied to those Methods. But Methods can still be defined in subclass though those Methods will not be the overridden Method. Instead it defines a new Method.

  • Static Methods or variables do not take part in inheritance.

  • Even though static methods or variables do not take part in inheritance and cannot be overridden they can be redefined in subclass. The redefinition is not called overridden but hidden.

Last updated