3.8 Function overloading

The concept

Function overloading is one of the most important concepts in computer programming – and one of the most interviewed ones. The concept itself, is not very difficult though. Let’s have a look.


public class Dog
{
    public Integer age;
    private String name;
    private String gender;
    public String breed;
    public Boolean isPuppy;
    public static Integer dogCount = 0;
    
    public Dog()
    {
        dogCount++;
    }
    
    public Dog(String name) 
    {
        this();
        this.name = name;
    }
    
    public Dog(String name, Integer age)
    {
        this(name);
        this.age = age;
    }
    //...
    
    public void greeting()
    {
        System.debug('Hello, my name is ' + name);
    }
    
    public void greeting(String masterName)
    {
        System.debug('Hello ' + masterName + ', my name is ' + name);
    }
    //...
}
    

In our anonymous block:

Dog d = new Dog();
Dog anotherDog = new Dog('Crazy');
Dog thirdDog = new Dog('Fluffy');
anotherDog.greeting();
thirDog.greeting('Dave');

Execute the above the code and take a look at the result!

A bit explanation

Function overloading means using the same function name, but different parameter list. Compiler can distinguish the call by the function’s parameter list.

A function can call its overloaded sibling.

If a constructor calls its overloaded sibling, it should be using the keyword – this.

Exercise

In our previous Person class, create more constructors and overloaded functions.

Subscribe to Sfdcinpractice

Subscribe to get the latest blogs and tutorials of sfdcinpractice. No spam, no trash, only the awesome posts from sfdcinpractice. 

Leave a Reply

Your email address will not be published / Required fields are marked *