Java interface design
LOL in design time, the offensive hero category, there are two, one is the physics department carried out the attack, one way is to attack magic system
At this time, you can use the interface to achieve this effect.
The interface is like a convention, we agreed to some of the Department of Physics hero is a hero, then they will be able to carry out physical attacks.
Step 1: physical attack Interface
Create an interface File-> New-> Interface
AD, declare a method physicAttack physical attacks, but there is no method body, it is an " empty " approach
package charactor;
public interface AD {
//物理伤害
public void physicAttack();
}
Step 2: a class of the hero, physical attacks can be used
Design of a class of hero, physical attacks may be used, such LOL hero called AD in the
classes: ADHero
inherits Hero class, inherited name, hp, armor and other properties
Implement an interface, the equivalent of some kind of commitment agreement
So, to achieve the AD this interface, you must provide the AD method declared in the interface physicAttack ()
implement the use of keywords on grammar implements
package charactor;
public class ADHero extends Hero implements AD{
@Override
public void physicAttack() {
System.out.println("进行物理攻击");
}
}
Step 3: Magic attack Interface
Create an interface File-> New-> Interface
the AP, declare a method magicAttack magic attacks, but there is no method body, it is an "empty" approach
package charactor;
public interface AP {
public void magicAttack();
}
Step 4: Design a class hero, you can only use magic attacks
Design for a Class Heroes, can only use magic attacks, these heroes are called in LOL in AP
classes: APHero
inherited Hero class, inherited the name, hp, armor and other property
, while achieving the AP this interface, you must provide the AP interface method declared magicAttack ()
package charactor;
public class APHero extends Hero implements AP{
@Override
public void magicAttack() {
System.out.println("进行魔法攻击");
}
}
Step 5: Design a class heroes, not only physical attacks, magic attacks can be
Heroic, capable of physical attacks and magic attacks at the same time
such Izawa Riel, Paper City policewoman Caitlin
package charactor;
//同时能进行物理和魔法伤害的英雄
public class ADAPHero extends Hero implements AD,AP{
@Override
public void magicAttack() {
System.out.println("进行魔法攻击");
}
@Override
public void physicAttack() {
System.out.println("进行物理攻击");
}
}
Exercise : Interface
(Designing a treatment Interface: Healer
The interface has a method declaration: heal ()
Support design a class that represents support hero, inheritance Hero class, while achieving a Healer this interface)
The answer :
public interface Healer {
public void heal(); //加血
}
.
public class Support extends Hero implements Healer{
@Override
public void heal() {
System.out.println(name+" 加了一口血");
}
}