Course Content
Introduction to Java
Today we'll learn about something cool in Java programming - method and constructor overloading. Are you ready to learn? Let's go!
Method Overloading
Method overloading is when you have multiple methods with the same name but different parameters in the same class. This allows you to write multiple methods that perform different actions based on the parameters you pass to them.
For example, let's say you have a class called Toy
, and you want to write a method that sets the name and color of a toy. But you also want to write a method that sets the toy's name. You can use method overloading to do this.
Here's how it would look:
Main.java
In this example, we have two methods with the same name, setDetails
, but different parameters. So, depending on the parameters you pass, it will call the corresponding method. Let’s see how it works.
Main.java
In this example, we create a Toy object called t1
and call the setDetails
method with two parameters, "Car"
and "Red"
. This will call the first setDetails
method and set the name
and color
variables of the toy.
Main.java
In this example, we create another Toy object called t2
and call the setDetails
method with one parameter, Plane
This will call the second setDetails
method and set the name
variable of the toy.
Constructor Overloading
Constructor overloading is similar to method overloading but with constructors. Constructors are special methods when you create an object of a class. And with constructor overloading, you can write multiple constructors with different parameters to create objects differently.
For example, let's say you have a class called ToyBox
and want to create a ToyBox object with or without a maximum capacity. You can use constructor overloading to do this.
Here's how it would look:
Main.java
In this example, we have two constructors, one without any parameters and one with an int
parameter. So, depending on the parameters you pass when creating an object, it will call the corresponding constructor.
Let’s see how it happens with the following code.
Main.java
As you can see, the first ToyBox
object is created using the first constructor without any parameters, which sets the maxCapacity
to 100. The second ToyBox
object is created using the second constructor with a parameter, which sets the maxCapacity
to 200. The getMaxCapacity
method retrieves the value of the maxCapacity
variable.
And that's it! You now know about the method and constructor overloading in Java. Remember, method overloading allows you to write multiple methods with the same name but different parameters, and constructor overloading allows you to write multiple constructors with different parameters to create objects differently.
What is method overloading in Java?
Select the correct answer
What is constructor overloading in Java?
Select the correct answer
Section 3.
Chapter 2