1、用局部内部类技术。
class a implements Lights{
public void shine(){
System.out.println("shine in red ")
}
}
lamp.on(new a());
2、用匿名内部类技术。
lamp.on(new Light(){
void shine(){
System.out.println("shine in yellow")
}
});
结果:
in method
ma in anonymous innerr class
in method
ma in local inner class
A、B
//猎人和僵尸
//猎人类
package org.jsoft.HW;
public class Hunter {
private String name;
private int life;
private String weapon;
private boolean isLive;
public void setName(String name ){
this.name=name;
}
public void setLife(int life){
this.life=life;
}
public void setWeapon(String weapon){
this.weapon=weapon;
}
public void setIsLive(boolean isLive){
this.isLive=isLive;
}
public String getName(){
return name;
}public int getLife(){
return life;
}
public String getWeapon(){
return weapon;
}
public boolean getIsLive(){
return isLive;
}
public Hunter(String name,int life,String weapon ){
this.name=name;
this.life=life;
this.weapon=weapon;
}
public void fight(Monster monster){
int a ;
a=this.life-monster.getLife();//将猎人的血量减去僵尸的血量赋值给a
this.life=a;//此时猎人剩余的血量为a.
if(a>0){//如果a>0则说明猎人活着
this.isLive=true;
}else//否则猎人死亡。
{
this.isLive=false;
}
}
public void injured(){//受伤
}
public void dead(){//死亡
}
public void show(){//显示猎人的状态
if(this.isLive==true){//如果猎人活着。显示猎人的血量
System.out.println("猎人剩余血量:"+this.name+"还剩"+this.life+"滴血");
}
else{//否则猎人死亡.
System.out.println(this.name+"死亡"");
}
}
}
//僵尸类
package org.jsoft.HW;
public class Monster {
private String type;
private boolean isLive;
private int life;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public boolean isLive() {
return isLive;
}
public void setLive(boolean isLive) {
this.isLive = isLive;
}
public int getLife() {
return life;
}
public void setLife(int life) {
this.life = life;
}
public Monster(String type,int life){
this.type=type;
this.life=life;
}
public void injured(){
//受伤
}public void kill(Hunter hunter){
//还击
if(hunter.getLife()<0){
this.isLive=true;
this.life=Math.abs(hunter.getLife());//如果僵尸没死。(此时猎人的血量是负数)猎人血量的绝对值等于僵尸剩余血量
}
else{
this.isLive=false;
}
}public void dead(){
//死亡
}
public void show(){
//显示状态
if(this.isLive==true){//如果僵尸没死,则输出僵尸剩余血量
System.out.println("僵尸剩余血量:"+this.type+"还剩"+this.life+"滴血");
}
else{//否则输出僵尸死亡。
System.out.println(this.type+"死亡");
}
}
}
//测试类
package org.jsoft.HW;
public class TestGame {
public static void main(String[] args) {
// TODO Auto-generated method stub
Hunter h=new Hunter("李辉",400,"大砍刀");
Monster m=new Monster("哥布林", 300);
h.fight(m);
m.kill(h);
System.out.println("猎人的状态:");
h.show();
System.out.println("僵尸的状态:");
m.show();
}
}
控制台输出