Skip to main content

Overloading and Overriding with Polymorphism in java

Polymorphism is a Greek word. Poly means many moprhism means form. In java one form is using for multiple uses is called polymorphism. It is mainly two types. That are called
            •  Compile time polymorpshism/static polymorpshism
            • Runtime polymorphism/dynamic polymorphism

          Static polymorphism is called the overloading and dynamic polymorphism is called overriding in java.  At the time of method overloading java compiler will understand which  method is calling, is called static polymorphism. At the time of compilation java compiler will not identifies which method is calling exactly, that will understand JVM at the time of runtime is called Overriding in java.

            Overloading again two types, that are method overloading and constructor overloading. But, constructors we can't override in java, because of ambiguity.

Method Overloading: Which of two or more methods declared with the same method name with different signature is called as method overloading.

Here is the example for showing simple method overloading:
package com.javatbrains.polymorpsism;

public class MethodOverloading {

     public void add(){
          System.out.println("No parameters");
     }
    
     public void add(int a){
          System.out.println("Single parameter: "+a);
     }

     public static void main(String[] args) {
          MethodOverloading mo = new MethodOverloading();
          mo.add();
          mo.add(10);
     }

}
OutPut:
     No parameters
     Single parameter: 10


Here is the another example for method overloading:

package com.javatbrains.polymorphism;

public class MethodOverloading1 {
    
     public void meth(int a){
          System.out.println("First method value: "+a);
          float f = meth(a, 20.0f);
          System.out.println("Second method value: "+f);
     }
    
     public float meth(int a, float b){
          float i = a+b;
          return i;
     }
     public static void main(String[] args) {
          MethodOverloading1 mo1 = new MethodOverloading1();
          mo1.meth(10);
     }

}
OutPut:
     First method value: 10
     Second method value: 30.0

Here we will see how to overload the main method:

package com.javatbrains.polymorphism;

public class OverloadingMain {
    
     public static void main(){
          System.out.println("Inside the no parameter");
          main(1);
     }
    
     public static int main(int a){
          System.out.println("Inside the single parameter");
          return a;
     }
    
     public static void main(String[] args) {
          System.out.println("Inside the array parameter");
          main();
     }

}
OutPut:
     Inside the array parameter
     Inside the no parameter
     Inside the single parameter

Constructor Overloading: Two or more constructors declared with same name and different signature is called constructor overloading.

package com.javatbrains.polymorphism;

public class ConstructorOverloading {

     public ConstructorOverloading(){
          System.out.println("Inside the default constructor");
     }
    
     ConstructorOverloading(float a){
          System.out.println("Inside the second constructor");
     }
     public static void main(String[] args) {
          //Default constructor will call at the time of creating first object
          ConstructorOverloading first = new ConstructorOverloading();
          //parameter constructor will call at the time of creating second constructor
          ConstructorOverloading second = new ConstructorOverloading(15.0f);
     }

}
OutPut:
     Inside the default constructor
     Inside the second constructor

         
          In the above example will shows how to do constructor overloading in java for class ConstructorOverloading.java. There are two constructors called one is default constructor and another one is parametrised constructor which contains one or more parameters.

Points to remember about Overloading:
            • Methods signature should be different
            • method names should be same in overloading, otherwise those methods will not be under overloading.
            • Return type will be same or not.

The above all conditions also applicable for constructor overloading. But, constructors doesn't have any return type.

Here is the overloading failure scenario:

package com.javatbrains.polymorphism;

public class FailureOverloading {

     public static void add(int i, float j) {
          System.out.println("First method: " + (i + j));
     }

     public static void add(float i, int j) {
          System.out.println("Second method: " + (i + j));
     }

     public static void main(String[] args) {
          add(10, 10);  //Failure because of ambiguty
     }

}
OutPut:
    Compilation fails because of ambiguty. While passing the values from main method you need to specify which one int and float.

Overriding in java:
          Which of two or more methods declared with same name and same method signature is called method overriding. Overriding will be happens in between the child and parent classes.

Points to remember about Overriding:
            • Methods name should be same
            • Methods signature should be same
            • Methods return type should be same
            • Static method should not be overridden
            • Cannot override final method
            • Cannot override constructors

Here is the signature to understand about the overriding in java.

    package com.javatbrains.polymorpshism;

    class A{
        void abc(){}
    
        void xyz(int a){}
    }

    class B extends A{
        void abc(){}
    
        void xyz(int a){}
    }


For example, see the below example:

package com.javatbrains.polymorphism;

class Movie {
    
     public void actor() {
          System.out.println("Inside movie class actor");
     }

     public String actress(String name) {
          System.out.println("Inside movie class actress");
          return name;
     }
}

class Theater extends Movie {
     @Override
     public void actor() {
          super.actor(); //For calling super class method in subclass
          System.out.println("Inside theater class actor");
     }

     @Override
     public String actress(String name) {
          super.actress(name); //For calling super class method in subclass
          System.out.println("Inside theater class actress: "+name);
          return name;
     }
}

public class Overriding {

     public static void main(String[] args) {
          Movie m = new Theater();
          m.actor();
          m.actress("Kajol");
     }

}
OutPut:
     Inside movie class actor
     Inside theater class actor
     Inside movie class actress
     Inside theater class actress: Kajol
         
          Above example shows you how to do method overriding in java. There are two classes which represents the parent called Movie and child class as Theater. This example also shows you how to use inheritance in java. Here,  Theater class is inheriting Movie class and all the Movie class methods are overriding in Theater class.

          There I am using the super keyword for calling the super class method or variable from subclass.

          If you want to know how to override the interface methods in java, follow with the interfaces post in the same blog.

Related Posts:

Comments

Popular posts from this blog

Multithreading in java with example

Multithreading  is one of the most important concept in core java. In this article we will learn what is multithreading? , what is the use of it? and What is the use of Synchronization and when to use it?  with detailed examples. At a time, two or more threads are accessing the same object is called as Multithreading  in Java .  First, we will create two threads for two objects. It is also possible to run two or more threads on a single class object. In this case, there is a possibility to get unreliable results. If the two threads are perform same task, then they need same object to be executed each time. For your better understanding, take an example of any reservations like, railway, movie ticket booking,etc. Let us think only one berth is available in a train and two passengers are asking for that berth. The first person has sent a request to allocate that ticket/berth to him. At the same time, the second person also sent a request to allocate that ...

Git installation for AngularJS 2 in Windows 10

Download Git latest version from https://git-scm.com/downloads or you click on the below link to download directly for windows https://git-scm.com/download/win . Once download completes, click on executable file to start installation process and choose Yes to allow the software installation in windows 10. Click on Next button to continue further installation. Browse the isntallation directory and click on Next button to continue. Select the list of components which you want to be installed and click on Next button to proced further installation. Type the shortcut name for Start menu and click on Next button. Select how you want to use the Git and click on Next button. For Windows no need to change anything, let it be the default one. Choose the Use the OpenSSL library and click on Next button. Select how should Git treat line ending in text files and click on Next button. Select which terminal emulator to use with Git and click on Next button. Configure extr...

JNDI configuration for Tomcat 9 with Oracle

In this article, I am going to place the required source code to get data from the table by using the JNDI configuration. Below are the environment details that I have configured currently. Windows - 7 Oracle - 10g Tomcat - 9 JDK - 8 Eclipse Oxygen Ojdbc6 jar required First, we need to create the Dynamic Web Project. If you don't know how to do <Click Here>. I have faced a lot of issues before getting the output like 405, No driver class to load, etc. I am using JSP & Servlets in the current explanation. Before started writing the application logic, we need to do the below configuration in the installed tomcat directory. Place OJDBC6.jar in the Tomcat LIB directory. Add this Resource under <GlobalNamingResources> in Server.xml file which is present under the conf directory in Tomcat. < Resource name = "jdbc/myoracle" global= "jdbc/myoracle" auth = "Container" type= "javax.sql.DataSource" driverClass...