1. Gyanastra
  2. Programming Languages
  3. Object Oriented Concepts
  4. Inheritance and Polymorphism
Free lesson, no account needed 11 min read 12 practice questions after it
Asked in past papers9 times
  • ISRO20172009
  • UGC NET2019201820162015201320062004

Programming Languages · Object Oriented Concepts

Inheritance and Polymorphism

Overview

Inheritance and polymorphism are two pillars of object-oriented programming. Inheritance lets a class reuse and extend another class, while polymorphism lets one interface serve objects of different classes.
UGC NET tests definitions, inheritance-type recognition, constructor order, access rules, binding time, and language rules in C++ and Java.
Before this lesson, know classes, objects, methods, access specifiers, and the difference between the static type of a reference and the dynamic type of its object.
These notes use standard C++11-and-later and Java 8-and-later conventions; where older Java versions differ, the difference is stated.

Key concepts

  • Class is a blueprint; object is an instance. A base class, superclass, or parent class is inherited from; a derived class, subclass, or child class inherits from it.
  • Inheritance is the mechanism by which a derived class automatically acquires accessible members of its base class and may add or modify behaviour.
    It models an is-a relationship: if SavingsAccount inherits BankAccount, then a savings account is-a bank account.
  • Composition/aggregation models has-a or part-whole; it is not inheritance. Inheritance gives reusability, extensibility, generalization (base class) and specialization (derived class).
  • The five standard inheritance types are single, multiple, multilevel, hierarchical, and hybrid. Java supports single class inheritance only, but multiple interface implementation; C++ supports multiple class inheritance.
  • Access specifiers: a private member is accessible only within its own class, not directly by a derived class; a protected member is accessible in derived classes and, in Java, also within the same package; a public member is accessible everywhere.
    In C++, inheritance mode public, protected, or private changes the effective access of inherited members; base private members remain directly inaccessible in all modes.
  • Constructors are not inherited. When a derived object is created, the base class constructor runs first, then the derived class constructor. Destruction is the reverse: derived destructor first, then base destructor.
    In C++, deleting through a base pointer requires a virtual destructor for defined behaviour.
  • Polymorphism means “many forms”: the same interface or method name can behave differently for different object types.
    Compile-time polymorphism uses static binding/early binding; runtime polymorphism uses dynamic binding/late binding.
  • Function overloading means several functions with the same name but different parameter lists in the same scope/class. It is compile-time polymorphism. Return type alone cannot distinguish overloads.
    Operator overloading gives an existing operator a new meaning for a user-defined type; it is also compile-time polymorphism.
  • Function overriding means a derived class defines a method with the same name and same signature as a base-class method. It supports runtime polymorphism.
    In C++ the base method must be virtual for dynamic dispatch through a base pointer/reference; in Java, instance methods are virtual by default.
  • Dynamic binding means the method executed depends on the actual object type at runtime, not only on the reference type. It requires inheritance, overriding, a base reference/pointer, and virtual dispatch in C++.
  • Method hiding is different from overriding: static methods in Java are hidden, not overridden; fields are shadowed and accessed according to the reference type, not the object type.
  • Java final class cannot be extended; final method cannot be overridden; final variable cannot be reassigned.
    An abstract class cannot be instantiated and may contain abstract methods; an interface declares a contract, and its methods are implicitly public and abstract before Java 8, so an implementing method must be public.
  • The Object class is the root of all Java classes. equals(Object) is the override signature; equals(SomeSpecificType) is an overload, not an override. This distinction decides whether Java uses reference equality or custom equality.

How it works

  1. Declare the base class with its fields and methods, choosing access specifiers carefully.
  2. Declare the derived class using class Derived : public Base in C++ or class Derived extends Base in Java. Use implements in Java for interfaces.
  3. When a derived object is created, memory contains the base-class subobject plus the derived-class fields. The base constructor initializes the base part first.
  4. Run the derived constructor body. If the base has no default constructor, the derived constructor must explicitly call a base constructor: super(...) in Java or an initializer list in C++.
  5. At a method call, the compiler first uses the static type of the reference/pointer to resolve overloads and access checks.
    If the chosen method is overridden and dynamic dispatch applies, the runtime actual object type selects the executed method.
  6. Destroy the object in reverse order. In C++, make the base destructor virtual if deletion may occur through a base pointer.
  7. Enforce access rules at compile time: private members are reached through base-class public/protected methods, not directly.
Figure. Notice the compiler first resolves overloads using static types. If an overridden instance method is C++ virtual or a Java instance method, runtime actual object type selects the executed method; otherwise binding is static.

Worked examples

Example 1 — Match the inheritance type.
List-I: A. Single, B. Multilevel, C. Hierarchical, D. Multiple.
List-II: i. One base, many derived classes; ii. One base, one derived class; iii. A derived class has two or more base classes; iv. A chain such as A → B → C.
Match: A-ii, B-iv, C-i, D-iii. Single has one parent and one child; multilevel forms a chain; hierarchical has one parent with several children; multiple has several parents for one child. A combination such as multilevel plus multiple is hybrid.

Example 2 — Statement evaluation.
Statement I: “When a derived object is created, the derived constructor runs before the base constructor.”
Statement II: “Overloading is resolved at compile time.”
Statement III: “Overriding is resolved at runtime when dynamic dispatch is available.”
I is false: the base constructor runs first. II is true: the compiler chooses the overload from the parameter list. III is true: overriding uses the actual object type when the method is virtual/dynamic. Answer: only II and III are true.

Example 3 — Java field hiding versus method overriding.

class Account {
    int rate = 5;
    void show() { System.out.println("Account"); }
}
class SavingsAccount extends Account {
    int rate = 7;
    void show() { System.out.println("Savings"); }
}
public class Test {
    public static void main(String[] args) {
        Account a = new SavingsAccount();
        System.out.println(a.rate);
        a.show();
    }
}

Output:

5
Savings

a.rate is a field: fields are not polymorphic, so the static type Account selects Account.rate, giving 5. a.show() is an overridden instance method: Java dispatches to SavingsAccount.show(), giving Savings.

Example 4 — Hard two-step: overload versus override with equals.

class Money {
    int rupees;
    Money(int r) { rupees = r; }
    public boolean equals(Money other) {
        return this.rupees == other.rupees;
    }
}
public class Check {
    public static void main(String[] args) {
        Money m1 = new Money(500);
        Money m2 = new Money(500);
        Object o1 = new Money(500);
        Object o2 = new Money(500);
        System.out.println(m1.equals(m2));
        System.out.println(o1.equals(o2));
        System.out.println(m1.equals(o2));
    }
}

Output:

true
false
false

equals(Money) does not override Object.equals(Object) because the parameter type differs; it overloads it. For m1.equals(m2), both static types are Money, so the compiler selects equals(Money) and returns true.
For o1.equals(o2), the static type is Object, so only Object.equals(Object) is selected; it compares references and returns false. For m1.equals(o2), equals(Money) is not applicable because o2 has static type Object; the compiler selects Object.equals(Object), which again returns false.
To override correctly, write public boolean equals(Object o) with an instanceof check and cast.

Example 5 — C++ virtual versus non-virtual call.

#include <iostream>
using namespace std;
class Base {
public:
    void show() { cout << "Base" << endl; }
    virtual void display() { cout << "BaseD" << endl; }
    virtual ~Base() {}
};
class Derived : public Base {
public:
    void show() { cout << "Derived" << endl; }
    void display() override { cout << "DerivedD" << endl; }
};
int main() {
    Derived d;
    Base* p = &d;
    p->show();
    p->display();
    return 0;
}

Output:

Base
DerivedD

show() is non-virtual, so p->show() is bound statically to Base::show. display() is virtual, so p->display() is bound dynamically to Derived::display.

Comparison

FeatureOverloadingOverriding
MeaningSame name, different parameter listsSame name and same signature in a derived class
ScopeUsually same class/scopeBase and derived classes
Inheritance neededNoYes
BindingCompile time/staticRuntime/dynamic when virtual dispatch applies
Return typeCannot differ aloneMust be compatible; covariant return allowed in Java/C++
AccessIndependent overloadsCannot be more restrictive in the override
C++ requirementNone specialBase method must be virtual for runtime dispatch
Java requirementNone specialInstance method; not static, private, or final
AspectCompile-time polymorphismRuntime polymorphism
Also calledStatic/early bindingDynamic/late binding
Achieved byOverloading, operator overloading, templates/genericsOverriding through base reference/pointer
Decision made byCompiler, using static typesRuntime, using actual object type
FlexibilityLess flexibleMore flexible
Typical C++ toolOverloaded functionsvirtual functions
Typical Java toolOverloaded methodsOverridden instance methods
Java termRule
final classCannot be extended
final methodCannot be overridden
abstract classCannot be instantiated; may contain abstract methods
InterfaceContract; methods implicitly public and abstract before Java 8; implementing method must be public
Class inheritanceA class extends exactly one class
Interface inheritanceA class may implement many interfaces

Revision summary

  • Inheritance is is-a; composition/aggregation is has-a.
  • Five inheritance types: single, multiple, multilevel, hierarchical, hybrid.
  • Base constructor first; derived destructor first.
  • Overloading = compile time; overriding = runtime with dynamic dispatch.
  • Return type alone cannot overload a method.
  • Java: one class extended, many interfaces implemented; final blocks extension/overriding.
  • Private members are not directly accessible in a subclass.
  • Fields and static methods are not polymorphic; overridden instance methods are.
  • C++ needs virtual; Java instance methods are virtual by default.
  • equals(Object) overrides; equals(SpecificType) overloads.
  • Static type controls overload resolution and field access; actual type controls overridden method calls.

Previous-year exam insights

  • Direct definition questions ask whether inheritance is an is-a relationship, what polymorphism means, and what function overloading is; answer from the precise one-line definitions, not from examples alone.
  • Statement I/II/III questions often mix constructor order, final, interface implementation, overloading and overriding.
    Check each statement independently; one reversed constructor order can make a whole option wrong.
  • Match List-I with List-II questions test inheritance types, binding types, and terms such as overloading, overriding, abstraction and encapsulation.
    Learn the exact defining phrase for each term.
  • Assertion–Reason questions often claim that overloading is runtime polymorphism or that overriding is compile-time binding; both are false.
    Overloading is static, overriding is dynamic when dispatch applies.
  • Code-output questions test static versus dynamic type: base reference to derived object, field hiding, equals overload versus override, and C++ virtual versus non-virtual calls.
    Trace the static type first, then the actual type.
  • Common traps: “derived constructor runs first” is false; “overloading is dynamic” is false; “final class can be extended” is false; “overriding uses different parameters” is false; “private members are directly inherited” is false; “Java class extends multiple classes” is false.
  • Check first whether the question is about overloading or overriding, then whether binding is static or dynamic, then whether the reference type is base or derived, and finally whether the language uses virtual, final, or interface rules.

Practice at PARIKSHA

You are ready for the PARIKSHA tests of this sub-topic when you can:

  • Define inheritance, polymorphism, overloading and overriding in one precise line each.
  • Identify single, multiple, multilevel, hierarchical and hybrid inheritance from a class diagram.
  • State the constructor and destructor order for a derived object in C++ and Java.
  • Decide whether a given method call is compile-time or runtime bound.
  • Compare overloading and overriding by scope, signature, binding, return type and access.
  • Apply Java rules for final, abstract, interfaces and single class inheritance.
  • Trace output when a base reference points to a derived object, including field hiding and overridden methods.
  • Explain why equals(SpecificType) is an overload and equals(Object) is an override, and predict the output.
  • Distinguish C++ virtual and non-virtual calls through a base pointer.
  • Spot false statements about constructor order, binding time, access and multiple inheritance.

Attempt the sub-topic test first, then the subject test.

Pages 1–2 of 2