Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
Compile Time Polymorphism in Java
Next article icon

Compile Time Polymorphism in Java

Last Updated : 12 Mar, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Polymorphism in Java refers to an object's capacity to take several forms. Polymorphism allows us to perform the same action in multiple ways in Java.

Polymorphism is divided into two types:

  • Compile-time polymorphism
  • Run time polymorphism

Note: Run time polymorphism is implemented through Method overriding. Whereas Compile Time polymorphism is implemented through Method overloading and Operator overloading.

In this article, we will see Compile-time polymorphism.

Compile-time Polymorphism

Compile-time polymorphism is also known as static polymorphism or early binding. Compile-time polymorphism is a polymorphism that is resolved during the compilation process. Overloading of methods is called through the reference variable of a class. Compile-time polymorphism is achieved by method overloading and operator overloading.

1. Method overloading

We can have one or more methods with the same name that are solely distinguishable by argument numbers, type, or order.

Method Overloading occurs when a class has many methods with the same name but different parameters. Two or more methods may have the same name if they have other numbers of parameters, different data types, or different numbers of parameters and different data types. 

Example: 

void gfg() { ... }
void gfg(int num1 ) { ... }
void gfg(float num1) { ... }
void gfg(int num1 , float num2 ) { ... }

a. Method overloading by changing the number of parameters 

 In this type, Method overloading is done by overloading methods in the function call with a varied number of parameters.

 Example:

show( char a )
show( char a ,char b )

 In the given example, the first show method has one parameter, and the second show method has two methods. When a function is called, the compiler looks at the number of parameters and decides how to resolve the method call.

Java
// Java program to demonstrate the working of method // overloading by changing the number of parameters   public class MethodOverloading {            // 1 parameter     void show(int num1)     {         System.out.println("number 1 : " + num1);     }      // 2 parameter     void show(int num1, int num2)     {         System.out.println("number 1 : " + num1                            + "  number 2 : " + num2);     }      public static void main(String[] args)     {         MethodOverloading obj = new MethodOverloading();                  // 1st show function         obj.show(3);                   // 2nd show function         obj.show(4, 5);      } } 

Output
number 1 : 3 number 1 : 4  number 2 : 5

In the above example, we implement method overloading by changing several parameters. We have created two methods, show(int num1) and show(int num1, int num2). In the show(int num1) method display, one number and the void show(int num1, int num2) display two numbers.

b. Method overloading by changing Datatype of parameter

In this type, Method overloading is done by overloading methods in the function call with different types of parameters.

Example:

show( float a float b)
show( int a, int b )

In the above example, the first show method has two float parameters, and the second show method has two int parameters. When a function is called, the compiler looks at the data type of input parameters and decides how to resolve the method call.

Program:

Java
// Java program to demonstrate the working of method // overloading by changing the Datatype of parameter  public class MethodOverloading {        // arguments of this function are of integer type     static void show(int a, int b)     {         System.out.println("This is integer function ");     }        // argument of this function are of float type     static void show(double a, double b)     {         System.out.println("This is double function ");     }        public static void main(String[] args)     {         // 1st show function         show(1, 2);                // 2nd show function         show(1.2, 2.4);     } } 

Output
This is integer function  This is double function 

In the above example, we changed the data type of the parameters of both functions. In the first show() function datatype of the parameter is int. After giving integer type input, the output will be ' This is integer function.' In the second show() function datatype of a parameter is double. After giving double type input, the output would be 'This is double function.' 

c. By changing the sequence of parameters 

In this type, overloading is dependent on the sequence of the parameters. 

Example:

show( int a, float b ) 
show( float a, int b )

Here in this example, The parameters int and float are used in the first declaration. The parameters are int and float in the second declaration, but their order in the parameter list is different.

Java
// Java program to demonstrate the working of method // overloading by changing the sequence of parameters  public class MethodOverloading {      // arguments of this function are of int and char type     static void show(int a, char ch)     {         System.out.println("integer : " + a                            + " and character : " + ch);     }      // argument of this function are of char and int type     static void show(char ch, int a)     {         System.out.println("character : " + ch                            + " and integer : " + a);     }      public static void main(String[] args)     {         // 1st show function         show(6, 'G');          // 2nd show function         show('G', 7);     } } 

Output
integer : 6 and character : G character : G and integer : 7

In the above example, in the first show, function parameters are int and char, and in the second shoe, function parameters are char, and int. changed the sequence of data type. 

Invalid cases of method overloading:

Method overloading does not allow changing the return type of method( function ); it occurs ambiguity.

Examples

int sum(int, int);
String sum(int, int);

Because the arguments are matching, the code above will not compile. Both methods have the same amount of data types and the same sequence of data types in the parameters.

2. Operator Overloading 

Note: Operator Overloading is not supported in Java, in the following example we're trying to achieve the same functionality by the use of methods.

An operator is said to be overloaded if it can be used to perform more than one function other than the one its pre-defined for. Operator overloading is a mechanism through which we can change the meaning of a pre-defined operator and make it work for user-defined objects. In this example, we'll try to achieve the same by the use of method as Java does NOT support operator overloading.

Java
// Java program to demonstrate the // working of operator overloading  public class GFG {      // function for adding two integers     void add(int a, int b)     {         int sum = a + b;         System.out.println(" Addition of two integer :"                            + sum);     }      // function for concatenating two strings     void add(String s1, String s2)     {         String con_str = s1 + s2;         System.out.println("Concatenated strings :"                            + con_str);     }      public static void main(String args[])     {         GFG obj = new GFG();                // addition of two numbers         obj.add(10, 10);                // concatenation of two string         obj.add("Operator ", " overloading ");     } } 

Output
 Addition of two integer :20 Concatenated strings :Operator  overloading 

In the above example, the add method performs the addition between two strings achieving the same functionality as if '+' operator has been overloaded.

Advantages of Compile-time Polymorphism:

  • It improves code clarity and allows for the use of a single name for similar procedures.
  • It has a faster execution time since it is discovered early in the compilation process.

Disadvantages of Compile-time Polymorphism:

  • Limited dynamic behavior: It limits the dynamic behavior & flexibility of our code, allowing modifications only before the code is executed, hence it must be used by keeping certain factors in mind.
  • Maintenance issues: As the codebase grows, it can be quite difficult to manage and make any new modifications if we have too many overloaded methods.

Next Article
Compile Time Polymorphism in Java

D

dikshanandre2403
Improve
Article Tags :
  • Java
  • Java-Object Oriented
Practice Tags :
  • Java

Similar Reads

    Difference between Compile-time and Run-time Polymorphism in Java
    The word polymorphism means having many forms. In simple words, we can define polymorphism as the ability of a message to be displayed in more than one form. In this article, we will see the difference between two types of polymorphisms, compile time and run time. Compile Time Polymorphism: Whenever
    3 min read
    Dynamic Method Dispatch or Runtime Polymorphism in Java
    Prerequisite: Overriding in java, Inheritance Method overriding is one of the ways in which Java supports Runtime Polymorphism. Dynamic method dispatch is the mechanism by which a call to an overridden method is resolved at run time, rather than compile time. When an overridden method is called thro
    5 min read
    Interfaces and Polymorphism in Java
    Java language is one of the most popular languages among all programming languages. There are several advantages of using the java programming language, whether for security purposes or building large distribution projects. One of the advantages of using JA is that Java tries to connect every concep
    5 min read
    java.time.LocalTime Class in Java
    Java is the most popular programming language and widely used programming language. Java is used in all kinds of applications like mobile applications, desktop applications, web applications. As in Java, java.time.LocalTime class represents time, which is viewed as hour-minute-second. This class is
    5 min read
    java.time.Period Class in Java
    The Period Class in Java class obtains a quantity or amount of time in terms of years, months and days. The time obtained is a date-based amount of time in the ISO-8601 calendar system, such as '4 years, 5 months, and 6 days. The units which are supported for a period are YEARS, MONTHS, and days. Al
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences