Overloading and Overriding

JavaJavaBeginner
Practice Now

Introduction

In this lab, you will learn method overloading and method overriding. Overriding and overloading are two concepts used in Java programming language. Both the concepts allow programmer to provide different implementations for methods under the same name. Overloading happens at compile-time while overriding happens at runtime. Static methods can be overloaded but cannot be overridden. Overloading is a static bond while overriding is dynamic bond.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL java(("`Java`")) -.-> java/ProgrammingTechniquesGroup(["`Programming Techniques`"]) java(("`Java`")) -.-> java/ObjectOrientedandAdvancedConceptsGroup(["`Object-Oriented and Advanced Concepts`"]) java(("`Java`")) -.-> java/BasicSyntaxGroup(["`Basic Syntax`"]) java(("`Java`")) -.-> java/DataStructuresGroup(["`Data Structures`"]) java(("`Java`")) -.-> java/StringManipulationGroup(["`String Manipulation`"]) java(("`Java`")) -.-> java/SystemandDataProcessingGroup(["`System and Data Processing`"]) java/ProgrammingTechniquesGroup -.-> java/method_overloading("`Method Overloading`") java/ProgrammingTechniquesGroup -.-> java/recursion("`Recursion`") java/ProgrammingTechniquesGroup -.-> java/scope("`Scope`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/inner_classes("`Inner Classes`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/classes_objects("`Classes/Objects`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/class_methods("`Class Methods`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/inheritance("`Inheritance`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/modifiers("`Modifiers`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/oop("`OOP`") java/BasicSyntaxGroup -.-> java/identifier("`Identifier`") java/DataStructuresGroup -.-> java/arrays("`Arrays`") java/BasicSyntaxGroup -.-> java/comments("`Comments`") java/BasicSyntaxGroup -.-> java/data_types("`Data Types`") java/BasicSyntaxGroup -.-> java/operators("`Operators`") java/BasicSyntaxGroup -.-> java/output("`Output`") java/StringManipulationGroup -.-> java/strings("`Strings`") java/SystemandDataProcessingGroup -.-> java/system_methods("`System Methods`") subgraph Lab Skills java/method_overloading -.-> lab-178549{{"`Overloading and Overriding`"}} java/recursion -.-> lab-178549{{"`Overloading and Overriding`"}} java/scope -.-> lab-178549{{"`Overloading and Overriding`"}} java/inner_classes -.-> lab-178549{{"`Overloading and Overriding`"}} java/classes_objects -.-> lab-178549{{"`Overloading and Overriding`"}} java/class_methods -.-> lab-178549{{"`Overloading and Overriding`"}} java/inheritance -.-> lab-178549{{"`Overloading and Overriding`"}} java/modifiers -.-> lab-178549{{"`Overloading and Overriding`"}} java/oop -.-> lab-178549{{"`Overloading and Overriding`"}} java/identifier -.-> lab-178549{{"`Overloading and Overriding`"}} java/arrays -.-> lab-178549{{"`Overloading and Overriding`"}} java/comments -.-> lab-178549{{"`Overloading and Overriding`"}} java/data_types -.-> lab-178549{{"`Overloading and Overriding`"}} java/operators -.-> lab-178549{{"`Overloading and Overriding`"}} java/output -.-> lab-178549{{"`Overloading and Overriding`"}} java/strings -.-> lab-178549{{"`Overloading and Overriding`"}} java/system_methods -.-> lab-178549{{"`Overloading and Overriding`"}} end

Overloading

In the previous part, we have already used overloading in class Person as it had three constructors. That's a simple example. Overloading is a feature that allows a class to have more than one method with the same name. By means of this, we can handle different situations and won't be confused. Typically, there are three ways to achieve overloading:

  • Different number of parameters
  • Different types of parameters
  • Different order of different types of parameters

Example:

Write the following code in the /home/labex/project/overloadingTest.java file:

public class overloadingTest{
    public static void main(String[] args){
        overloadingTest test = new overloadingTest();
        System.out.println("add(10,20)= " + test.add(10,20));
        System.out.println("add(10,20,30)= " + test.add(10,20,30));
        System.out.println("add(5.5, 10.5)= " + test.add(5.5f, 10.5f));

        test.printInfo(1 , "an error!");
        test.printInfo("another error!" , 2);
    }
    // this method has two int params, returns an integer
    int add(int a, int b){
        return a+b;
    }
    // this method has three int params, returns an integer
    int add(int a, int b, int c){
        return a+b+c;
    }
    // this method has two float params, returns a float number
    float add(float a, float b){
        return a+b;
    }
    // this method has one string param and one int param, returns nothing
    void printInfo(String str, int code){
        System.out.println("Code: " + code + "\nMessage: " + str);
    }
    // this method has one int param and one string param, returns nothing
    void printInfo(int code, String str){
        System.out.println("Code: " + code + "\nMessage: " + str);
    }
}

Output:

Run the overloadingTest.java file using the following commands:

javac /home/labex/project/overloadingTest.java
java overloadingTest

See the output:

add(10,20)= 30
add(10,20,30)= 60
add(5.5, 10.5)= 16.0
Code: 1
Message: an error!
Code: 2
Message: another error!

Overriding

If a class inherits a method from its superclass, then there is a chance to override the method provided that it is not marked final or private. By overriding, we can define a behavior that's specific to the subclass, which means a subclass can implement a parent class method based on its requirement. In OOP, overriding means to override the functionality of an existing method. The return type should be the same or a subtype of the return type declared in the original (overridden) method in the superclass. The access level cannot be more restrictive than the overridden method's access level. For example: If a superclass method is declared public, then the overriding method in the subclass cannot be either private or protected. We also use the case of Animal (a simple version).

Example:

Write the following code in the /home/labex/project/overridingTest.java file:

class Animal{
    public void grow(){
        System.out.println("I'm animal, I grow up.");
    }
    public void sleep(){
        System.out.println("I'm animal, I am sleeping.");
    }
}
class Dog extends Animal{
    // overriding method
    public void grow(){
        System.out.println("I'm dog, I grow up.");
    }
}
class Bird extends Animal{
    // keep superclass grow(), add own statements
    // overriding method
    public void grow(){
        super.grow();
        System.out.println("I'm bird, I grow up.");
    }
    // overriding method
    public void sleep(){
        System.out.println("I'm bird, I am sleeping...");
    }
    // Bird own method
    public void sing(){
        System.out.println("I'm bird, I am singing a song...");
    }
}
public class overridingTest{
    public static void main(String[] args){
        Dog dog = new Dog();
        dog.grow();
        Bird bird = new Bird();
        bird.grow();
    }
}

Output:

Run the overridingTest.java file using the following commands:

javac /home/labex/project/overridingTest.java
java overridingTest

See the output:

I'm dog, I grow up.
I'm animal, I grow up.
I'm bird, I grow up.

Summary

To organize a big project needs good thought of architecting, so you should know the essential concepts covered in this lab. Overriding and overloading provide us with more flexibility to make use of methods.

Other Java Tutorials you may like