0
0
Javaprogramming~20 mins

Compile-time polymorphism in Java - Mini Project: Build & Apply

Choose your learning style9 modes available
Compile-time Polymorphism in Java
πŸ“– Scenario: Imagine you are creating a simple calculator program that can add numbers. Sometimes you want to add two numbers, and other times you want to add three numbers. Using compile-time polymorphism, you can create methods with the same name but different numbers of inputs.
🎯 Goal: Build a Java class called Calculator that demonstrates compile-time polymorphism by having two add methods: one that adds two integers and another that adds three integers.
πŸ“‹ What You'll Learn
Create a class named Calculator.
Inside Calculator, create a method add that takes two int parameters and returns their sum.
Inside Calculator, create another method add that takes three int parameters and returns their sum.
In the main method, create an object of Calculator and call both add methods with appropriate arguments.
Print the results of both method calls.
πŸ’‘ Why This Matters
🌍 Real World
Compile-time polymorphism is used in many software applications to simplify code and improve readability by using the same method name for similar actions with different inputs.
πŸ’Ό Career
Understanding method overloading is essential for Java developers as it is a fundamental concept used in designing flexible and reusable code.
Progress0 / 4 steps
1
Create the Calculator class with the main method
Create a public class called Calculator and add a public static void main(String[] args) method inside it.
Java
Need a hint?

Start by writing public class Calculator { and then add the main method inside.

2
Add the first add method with two parameters
Inside the Calculator class but outside the main method, create a public method called add that takes two int parameters named a and b and returns their sum as an int.
Java
Need a hint?

Write a method with signature public int add(int a, int b) and return a + b.

3
Add the second add method with three parameters
Inside the Calculator class but outside the main method, create another public method called add that takes three int parameters named a, b, and c and returns their sum as an int.
Java
Need a hint?

Create a method public int add(int a, int b, int c) that returns a + b + c.

4
Use both add methods and print the results
Inside the main method, create an object of Calculator named calc. Then call calc.add(5, 10) and store the result in an int variable named sumTwo. Next, call calc.add(3, 4, 5) and store the result in an int variable named sumThree. Finally, print both sumTwo and sumThree using System.out.println.
Java
Need a hint?

Create an object with new Calculator(), call both add methods, and print the results.