OOP Concept – Inheritance

Basics

Different kinds of objects often have a certain amount in common with each other. Tiger & Cow, for example share the characteristics of Animal; Yet each also defines additional features that make them different. Object-oriented programming allows classes to inherit commonly used state and behavior from other classes.

Inheritance provides a way to extend existing classes to make a new classes with specialized behavior. Inheritance creates a hierarchy of classes and helps you reuse the code of a parent class in a child class.

A Class inherits the attributes and behavior of its parent class or superclass. The attributes and behavior of the superclass need to be public or protected. Members of the superclass can be inherited with some restrictions.

Subclasses inherit the superclass members that are declared with no access modifiers, if the subclasses are in the same package as the superclass.

Example:

Tiger and Cow are the subclasses of the Animal class. Animal class contains all common behaviors and states that belong to animals [tiger or cow] however Tiger / Cow has distinct behaviors too. These are defined in their respective classes. Tiger & Cow classes are called subclasses because they are derived from the Animal class – the super class. They inherit the attributes and behavior of the Animal class. The subclasses may also define more attributes and behavior.

Syntax:
<<Access modifiers>> class <subclass name> extends <superclass name>

<<Access modifiers>> – default access [nothing] or public access [public keyword]

There are two types of inheritance, single inheritance and multiple inheritance.

Single Inheritance: A subclass inherits from a single class.
Multiple Inheritance: A class inherits from more than one immediate superclass.

HINT: Java classes cannot extend multiple classes. In Java, Only interfaces are allowed to extend multiple interfaces. Also, classes can implement multiple interfaces.

Although a subclass inherits all the members of its superclass, it cannot access the private member variables of the superclass. The public and protected member variables of the superclasses are accessible to a subclass. If the subclass is in the same package as the superclass, default members are also accessible.

Method Overridding

A subclass inherits members and methods from its superclass. However, a subclass can change the functionality of an inherited method by overriding the method.

Encapsulation allows an object to supply requested information to another object.
Overriding is the ability of a subclass to modify the behavior that it inherits from the superclass. By overriding a method, the developer is free to charge the implementations of the method in the subclass.

In Java terminology, the method in the subclass that has the same name and signature as a method in the superclass is called the overridding method. The method in the superclass is called the overridden method.

Example: Consider the class Employee that contains a method named calculateSalary. Consider Manager and Engineer subclasses that extend Employee Class. The process for calculating salary for Manager and Engineer are different from each other. And So, to solve this problem, you can override calculateSalary method of Employee class and provide different implementations in Manager and Engineer class seperately.

Guidelines for Overriding a Method

  • The overriding and overridden methods should have the same return type, method name, and the number, type, and order of arguments.
  • The overriding method should have equal or greater access than an overridden method.

‘Super’ Keyword

The ‘super’ keyword is used when a subclass needs to refer to its immediate superclass.

Constructor Overriding

Constructors contain code that initializes an object during instance creation. The object should be properly initialized. This is to ensure that the object is not in an invalid state and is usable.

A subclass calls a constructor defined by its superclass by using the ‘super’ keyword.

Syntax: super(arg 1, arg 2, ..);

In the displayed syntax, the super keyword specifies any arguments required by the constructors in the superclass. An implicit call to the zero argument is made, if the method does not appear on the first line of the subclasses constructor. The super method needs to be the first statement in a subclass constructor. These constructors run regardless of whether the super method exists. If the super method is not used, the default constructor of each superclass is automatically executed.

Final Classes

A Class than cannot have subclasses and the member variables of which cannot be overridden is called final class.
Similarly, methods and variables that cannot be overridden are called final methods and final variables, respectively.

When a class is declared as final, the class cannot be extended. Therefore, a final class cannot have subclasses. This provides security because other application developers cannot create subclasses for this final class or modify its behavior.

Example: String class in java.lang.String package. This class is declared as a final class because the authors of the class did not want anyone to extend it.

Syntax for Class: final class <Class Name>
Syntax for Method: final <return type> <method name>

Features of a Final Class In Short:

  • Restricts a class from being extended.
  • Prevents its methods from being overridden
  • Restricts the declaration of abstract methods.
  • Cannot be simultaneously declared as final and abstract.

HINT: Why Final class cannot have abstract methods?
This is because final classes cannot be extended and abstract methods need to be implemented in nonabstract subclasses.

Method lookup

Method lookup is the process that a Java program uses to identify the appropriate method to be invoked. The method lookup process in Java is derived from the inheritance hierarchy. Inheritance in Java is implemented by using the extends keyword.

Example:
class B extends A {…}
To denote that class B inherits from class A, you declare class B using the above syntax.

The method lookup process searches for the method in the class of the receiver object. If a matching method definition is not found, method lookup continues to look for the method in the superclass.

Java allows a subclass to access the methods and fields in the superclass by using the super keyword.

Fig 1.1
Fig 1.1
Let consider an example [Refer fig 1.1], class Vehicle is the base class that defines a variable wheels and a method displayDetails. Class Truck inherits from class Vehicle, and class Tanker inherits from class Truck. Although class Truck and class Tanker inherit from class Vehicle, the variable wheels declared in class Truck and class Tanker is local variable and does not refer to the variable wheels in the class Vehicle. Therefore, any reference to the variable wheels within a method of class Truck will refer only its local value.

To refer to wheels in Truck from within Tanker, you use the syntax super.wheels. Java casts this reference to the super type. Super.wheels is shorthand for ((Truck) this).wheels. However, you cannot use super to discover the value of wheels in Vehicle from within Tanker. To refer to the wheels in Vehicle from within Tanker, you use the syntax ((Vehicle)this).wheels from within Tanker.

The super keyword can be used to bypass the overridden version of a method in a subclass and run the version in the superclass. The super keyword can also be used to bypass a member variable in a subclass for accessing a member variable that has the same name in a superclass.

Suppose class Tanker contains the call super.displayDetails, this call actually invokes the method displayDetails in class Truck because Tanker has inherited it from Truck. If you use the syntax ((Vehicle) this).displayDetails(), it results in the execution of method displayDetails from Vehicle.

Related Post:
Introduction to OOP | Polymorphism | Encapsulation

Advertisements

16 responses to “OOP Concept – Inheritance

  1. Mohammed Suleman

    Good Explanation, Keep it up, And continue to help us like this

  2. Very Nice and it is in Easy to Understand Format.

    If you have more Example programs add to the List. It will be more usefull to all

  3. Pingback: OOP - Introduction « IDYN Solutions

  4. good stuff bro..keep coming

  5. good…it would be even better if it is exemplified

  6. thanks…

  7. Very nice It is very easy to unterstand.It is very helpful to us that means students.Please Give us Brief notes on advanced java

  8. It is very good, It would be more useful, if more concepts are explained in this manner, eg interfaces, funciton overloading, virtual function and much more… Any how it’s a good job keep it up.

  9. dhilip Kumar M

    Fair.

  10. More thanks, eazy understandable

  11. Mohammed Farooq

    Tigons are cross between Tigers and Lions. Tigons have some characteristics from both of them; like they can prey like tigers and play like lions. Also tigons cannot reproduce. Tigons unlike Tigers cannot swim but eats fish, meat and fruits.

    Identity Objects and use encapsulation so that the above criterions are met?

  12. nice way to explain OOp concepts.

  13. Nice Explanation on Inheritence.. Here is my explanation about OOPs Concept : Inheritance

  14. clear explanation.. good post.. thanks for sharing.. 🙂

  15. basics are the most important things to learn. it is building block for learning more complex things in software

  16. basics are the hardest to teach, very nice

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s