DEV Community

Tamilselvan K
Tamilselvan K

Posted on

Day-59 Today I Learned Method Overloading and Default Values in Java

1. Method Overloading

Method overloading is defining multiple methods with the same name but different parameter lists within a class. It is also called compile-time polymorphism. The methods must differ in

  • Number of parameters, or
  • Type of parameters, or
  • Both

2.Default Values

In Java, default values are the values automatically assigned to Global variables when they are declared but not initialized. Local variables do not get default values and must be initialized before use.

byte = 0
short = 0
int = 0
long = 0L
float = 0.0f
double = 0.0d
char = '\u0000'
String (or any object)= null
boolean = false

Example

public class SuperMarket  
{
    static String shopName = "Rajeshwari"; // static variable shared by all objects
    String prodName;                       // instance variable, default value is null
    int price;                             // instance variable, default value is 0

    public static void main(String[] args) 
    {
        SuperMarket product1 = new SuperMarket();

        // Method overloading examples
        product1.buy(10);          // Calls buy(int no)
        product1.buy(15,100);      // Calls buy(int no1, int no2)
        product1.buy(10.5);        // Calls buy(double dd)
        product1.buy(10.5f);       // Calls buy(double dd), float is converted to double

        // Printing different data types
        System.out.println(10);        // prints int
        System.out.println(10.5f);     // prints float
        System.out.println("hii");     // prints String
    }

    void buy(double dd){
        System.out.println("buy one double args " + dd);
    }

    void buy(int no){
        System.out.println("buy one args " + no);
    }

    void buy(int no1, int no2){
        System.out.println("buy two args " + no1 + " " + no2);
    }
}
Enter fullscreen mode Exit fullscreen mode

Output

buy one args 10
buy two args 15 100
buy one double args 10.5
buy one double args 10.5
10
10.5
hii

Top comments (0)