Java Examples - Method Overloading
First let's look at the definition of method overloading: if two methods have the same name but different parameters, then one method can be said to be an overload of the other. The details are as follows:
- The method names are the same
- The parameter types or the number of parameters differ
- The return types of the methods may differ
- The modifiers of the methods may differ
- The main method can also be overloaded
The following example demonstrates how to overload the info method of the MyClass class:
MainClass.java File
class
MyClass
{
int
height
;
MyClass
(
)
{
System
.
out
.
println
(
"
No-argument constructor
"
)
;
height
=
4
;
}
MyClass
(
int
i
)
{
System
.
out
.
println
(
"
The house height is
"
i
"
meters
"
)
;
height
=
i
;
}
void
info
(
)
{
System
.
out
.
println
(
"
The house height is
"
height
"
meters
"
)
;
}
void
info
(
String
s
)
{
System
.
out
.
println
(
s
"
: The house height is
"
height
"
meters
"
)
;
}
}
public
class
MainClass
{
public
static
void
main
(
String
[
]
args
)
{
MyClass
t
=
new
MyClass
(
3
)
;
t
.
info
(
)
;
t
.
info
(
"
Overloaded method
"
)
;
//
Overloaded constructor
new
MyClass
(
)
;
}
}
The output of the above code is:
房子高度为 3 米
房子高度为 3 米
重载方法: 房子高度为 3 米
无参数构造函数
Java Examples