Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Java Example – Method overloading

Java Examples - Method Overloading

Java Examples Java Examples

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 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 Java Examples