OOPS Concepts: Inheritance and Polymorphism


In this article, I will explain about what is inheritance with example, types of inheritance, single inheritance, multiple inheritance, What is polymorphism, types of polymorphism, Method overloading and Method Overriding with example.

What is Inheritance?

  • Inheritance means creating new classes from existing classes so that new classes will have same features as of existing classes. In Inheritance, object takes properties of existing object.
  • A class which is used for inheritance is called as super class or parent class and a class which inherits super class is called as sub class or child class.
  • Main advantage of inheritance is code reusability.
  • It is used to achieve runtime polymorphism.
  • For example, suppose we have three classes BMW, Mercedes and Audi which have same characteristics as of Car class like speed, brand name, gear. So Car class will be super class here and all other will become sub class of Car class
    Syntax:
    Write sub class name followed by extend keyword then super class name.
    Class <subclass> extends <superclass>
    Example: Suppose we have three class i.e. MainClass, Car and Mercedes
    Car:
    public class Car {
        public void print(){
            System.out.println("Car class print method executed");
        }
    }

    Mercedes:
    public class Mercedes extends Car{
    }

    MainClass:
    public class MainClass {
        public static void main(String[] args) {
            Mercedes m = new Mercedes();
            m.print();
        }
    }

    Output: Car class print method executed
    Here, program execution starts from MainClass as we have written main method in MainClass. First it will create object 'm' of Mercedes class(sub class). Then next statement is calling of print() method. But Mercedes class doesn't have print() method. But Mercedes(sub class) method extends Car class(super class). So he can access all the properties of Car class. That's why print method of car class gets executed.
  • If we create same method i.e. print() method in Mercedes class also then it will call Mercedes print method. This is called as 'Overriding'.
    Example:
    Car:
    public class Car {
        public void print(){
            System.out.println("Car class print method executed");
        }
    }

    Mercedes:
    public class Mercedes extends Car{
        public void print(){
            System.out.println("Mercedes class print method executed");
        }
    }

    MainClass:
    public class MainClass {
        public static void main(String[] args) {
            Mercedes m = new Mercedes();
            m.print();
        }
    }

    Output: Mercedes class print method executed
    Here, we have same method in both super and sub class. Now when we call print method of sub class Mercedes by using object 'm' it executes its own method. This is called as overriding of method.
  • Now if in this case we want to execute the method of super class then we need to use 'super' keyword.
    Example:
    Car:
    public class Car {
        public void print(){
            System.out.println("Car class print method executed");
        }
    }

    Mercedes:
    public class Mercedes extends Car{
        public void print(){
            super.print();
            System.out.println("Mercedes class print method executed");
        }
    }

    MainClass:
    public class MainClass {
        public static void main(String[] args) {
            Mercedes m = new Mercedes();
            m.print();
        }
    }

    Output: Car class print method executed
    Mercedes class print method executed
    As we have used super.print(),print method of super class gets executed with print method of Mercedes class(sub class).
  • Advantage of Inheritance: By inheritance, programmer can reuse super class code in subclass without rewriting it. So productivity of programmer is increased.

Types of Inheritance

  1. Single Inheritance
    In this type, sub classes get produces from single super class.
    For example, College is one super class and its department like Arts, Science and Commerce are sub class of College class.
    SingleInheritance
    Class Arts extends College
    Class Science extends College
    Class Commerce extends College
  2. Multiple Inheritances
    In this type, sub classes get produces from multiple super classes.
    For example,
    Super Class: Milk – Water – Sugar – CoffeeBeans
    Sub Class: Coffee
In java, single inheritance is available.
Multiple inheritances is not there in java because of below reasons
  • It leads to lot of confusion. As sub class is inherited from multiple super classes it becomes confusion to take which value of variable.
    For example, in above example coffee is inherited from four super classes i.e. milk, water, sugar, coffee beans. If milk and water both have same member like state then it will be confusion about which copy of state is available for coffee class.
  • Programmer can achieve multiple inheritances by using interfaces.
  • Also by using single inheritance repeatedly multiple inheritances can be achieved.

What is Polymorphism?

  • Poly means many and morphs means behavior. Polymorphism means performing one action using different ways.
  • It allows same word or symbol to be interpreted correctly in different situation based on context.
  • In Java, it is done by two ways.
    Two types of polymorphism
    1. Static binding – Checked at compilation time – Method overloading
    2. Dynamic binding – Checked at run time – Method overriding
  1. Method overloading
    • Method overloading is done by writing same method with different signatures. We can pass different parameter list in different signatures.
    • In method overloading, two methods having same signatures but different return types is not possible.
    • Method overloading is possible with super (parent) and sub (child) class.
    • Example:
      Class Account{
      Void get();{ //1
          }
      Void get(int i){ //2
          }
      Void get(int I, char c){ //3
          }
      Int get(char c){ //4
          }
      Void get(char c) //5
          }

      In above example, we have get() method which is having five different signatures. 1st, 2nd and 3rd methods are having same name but different signatures with same return type which is valid. 4th method is having different signature with different return type which is also valid. But 5th case is invalid as it is having same signature as of 4th but different return type.

  2. Method Overriding
    • It is called as runtime polymorphism.
    • Method overriding is done by writing same method with same signatures in different class with inheritance.
    • Overriding is possible only in inheritance.
    • Example:
      Suppose we have two classes. Class 'Saving' and 'Current'.
      public class Saving {
          public void display(){
              System.out.println("Saving class display method called");
          }
      }
      public class Current extends Saving{
          public void display(){
              System.out.println("Current class display method called");
          }
      }
    • Both the methods have same method display(). So in main program when we create object of Current class it will call method of Current class.
      public class Account {
          public static void main(String[] args) {
              Current c = new Current();
              c.display();
          }
      }
    • Output: Current class display method called
      As Current class extends the properties of Saving class it have access to all methods of Saving class. But as Current class is having same method as of Saving class it is overriding the definition of Saving-display() method. This is called as method overriding.


Attachments

Comments

Author: Venkiteswaran02 May 2016 Member Level: Diamond   Points : 3

Oops!! I got taken for a ride by reading the title. Frankly, I thought the article is about human psychology and multiple behaviour. Clean bowled. It turned out to be something related to computer programming.
Even then I did not lose heart. I thought; well, being a layman I may get to know something new by reading thge article. Let me say, again I am beaten. Even though I glanced from top to bottom, not even at one place did I see the expansion of OOPS.
For the benefit of laymen readers, at least let me give the full form of OOPs in this contest. OOP stands for Object Oriented Programming. It will be nice if the author realises the fundamental handicaps in such articles and notes it for coming with better, easily understandable, self explanatory article which may enthuse even beginners and laymen.
I hope this article is useful for those who know about OOPs.



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: