Overloaded method refers to the same method name, but not the same type of argument
Step 1: A method of overload attack
Step 2: variable number of arguments
Step 3: Practice - Treatment
Step 4: The answer - Treatment
Step 2: variable number of arguments
Step 3: Practice - Treatment
Step 4: The answer - Treatment
Step 1: Method Overload attack
There is a hero, called a physical attack hero ADHero
provides three ways to ADHero
Method name is the same, but not the same type of parameters
when calling the method of attack, based on the type and number of parameters passed automatically call the corresponding method
provides three ways to ADHero
public
void
attack()
public
void
attack(Hero h1)
public
void
attack(Hero h1, Hero h2)
|
Method name is the same, but not the same type of parameters
when calling the method of attack, based on the type and number of parameters passed automatically call the corresponding method
public
class
ADHero
extends
Hero {
public
void
attack() {
System.out.println(name +
" 进行了一次攻击 ,但是不确定打中谁了"
);
}
public
void
attack(Hero h1) {
System.out.println(name +
"对"
+ h1.name +
"进行了一次攻击 "
);
}
public
void
attack(Hero h1, Hero h2) {
System.out.println(name +
"同时对"
+ h1.name +
"和"
+ h2.name +
"进行了攻击 "
);
}
public
static
void
main(String[] args) {
ADHero bh =
new
ADHero();
bh.name =
"赏金猎人"
;
Hero h1 =
new
Hero();
h1.name =
"盖伦"
;
Hero h2 =
new
Hero();
h2.name =
"提莫"
;
bh.attack(h1);
bh.attack(h1, h2);
}
}
|
Step 2: variable number of arguments
If you want to attack more heroes, we need to design more methods, this class will become very cumbersome, like this:
At this time, a variable number of parameters can be used
only to design a method
public void attack (Hero ... heros)
a method as described above can represent all
the methods, the use of an array mode process operation parameters can heros
public
void
attack(Hero h1)
public
void
attack(Hero h1,Hero h2)
public
void
attack(Hero h1,Hero h2,Hero h3)
|
At this time, a variable number of parameters can be used
only to design a method
public void attack (Hero ... heros)
a method as described above can represent all
the methods, the use of an array mode process operation parameters can heros
public
class
ADHero
extends
Hero {
public
void
attack() {
System.out.println(name +
" 进行了一次攻击 ,但是不确定打中谁了"
);
}
// 可变数量的参数
public
void
attack(Hero... heros) {
for
(
int
i =
0
; i < heros.length; i++) {
System.out.println(name +
" 攻击了 "
+ heros[i].name);
}
}
public
static
void
main(String[] args) {
ADHero bh =
new
ADHero();
bh.name =
"赏金猎人"
;
Hero h1 =
new
Hero();
h1.name =
"盖伦"
;
Hero h2 =
new
Hero();
h2.name =
"提莫"
;
bh.attack(h1);
bh.attack(h1, h2);
}
}
|
More, click here for: https://how2j.cn/k/class-object/class-object-overload/291.html