Please disable adblock to view this page.

← Go home

Inheritance and Polymorphism in Java

java-display

May 2, 2017
Published By : Pratik Kataria
Categorised in:

Inheritance

  • It means that there is a relationship between multiple classes.
  • This lets you inherit or extend functionality from one class to another.
  • C++ supports multiple inheritance but Java supports only single inheritance.
  • Each class can extend or inherit functionality from only one other class.
  • This makes it easier to manage the code.
  • Each class can extend only one direct superclass.
  • However, Java allows classes to implement multiple interfaces.

About Inheritance

  • Inheritance relationship can be described as:
    • Parent/Child i.e. Parent has functionality and Child inherits it.
    • Base/Derived
    • Superclass/Subclass (Terms used in Java)
      • Superclass has original functionality
      • Subclass is inheriting Superclass’s functionality by extending it.

Polymorphism

  • Addresses an object as either supertype or subtype.
    • Example: List is an interface. ArrayList implements the interface. This is similar to superclass and subclass. One can declare an object as List but instantiate it as ArrayList. ArrayList is also List but vice versa is not true.
  • Increases code flexibility and resuability.

An Inheritance Relationship

  • Consider a Vehicle class. It does not explicitly extends any other class.
    • THIS MEANS IT IMPLICITLY EXTENDS OBJECT CLASS
  • As it implicitly extends object class, it has methods like toString().
  • toString() method is originally implemented in Object class. Vehicle inherits this method.
  • Vehicle can override toString() method and create its own version; but if it does not, then you can call toString() method as member of subclass.
  • Vehicle class is also a super class. Suppose it has sub classes like:
    • Bike
    • Car
    • Auto
  • So, Bike can call methods of Vehicle class but it can also call methods of Object class.

Superclasses

  • Superclasses don’t need special code.
  • If a class isn’t marked ‘final’, it can be extended.
  • It can have subclasses.
  • All fields and methods are inherited from the subclasses unless marked private.

Example

package vehicle;
public class Vehicle {
    private int id;
    private boolean tested = false;
    
    public int getWheels() {
        //...
    }
    
    public void setForTesting() {
        //...
    }
    
    public void isTested() {
        this.tested = true;
    }
    
}
  •  Use extends keyword in subclass declaration to create inheritance relationship
package vehicle;

public class Bike extends vehicle {
    //...
}
  • If you create instance of this subclass:
    • You can call the public methods.
    • You can’t reach private fields.