引用类对象
定义一个Hero类对象(有参构造中引用Wepon对象)
Wepon类中代码:
public class Wepon {
private String code;
public Wepon() {
}
public Wepon(String code) {
this.code = code;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
}
Hero实现类对象代码:
public class Hero {
private String name;
private int age;
private Wepon wepon;
public Hero() {
}
public Hero(String name, int age, Wepon wepon) {
this.name = name;
this.age = age;
this.wepon = wepon;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Wepon getWepon() {
return wepon;
}
public void setWepon(Wepon wepon) {
this.wepon = wepon;
}
public void attack()
{
System.out.println("年龄为"+age+"的"+name+"用"+wepon.getCode()+"攻击对方!");
}
}
主类代码:
public class Demo01Main {
public static void main(String[] args) {
Hero hero=new Hero();
Wepon wepon=new Wepon();
hero.setName("飞天小女警");
hero.setAge(9);
wepon.setCode("旋风腿");
hero.setWepon(wepon);
hero.attack();
}
}
显示效果:
年龄为9的飞天小女警用旋风腿攻击对方!
增强版本(使用多种方法调用类方法或接口方法以Hero举例):
定义一个接口:
代码:
public interface Skill {
void method();
}
接口实现类:
public class SkillImpl implements Skill {
@Override
public void method() {
System.out.println("Pia-pia-pia~impl");
}
}
Hero类代码:
public class Hero {
private String name;
private Skill skill;
public Hero() {
}
public Hero(String name, Skill skill) {
this.name = name;
this.skill = skill;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Skill getSkill() {
return skill;
}
public void setSkill(Skill skill) {
this.skill = skill;
}
public void attack()
{
System.out.println("我叫"+name+"我释放了");
skill.method();
System.out.println("打死了岗村宁次!");
}
}
主类实现的三种方法:
public class Demop01Main {
public static void main(String[] args) {
Hero hero=new Hero();
hero.setName("李云龙");
/* 1.使用实现类 SkillImpl tt=new SkillImpl();
hero.setSkill(tt);
hero.attack();*/
/* 2.匿名内部类: Skill skill=new Skill() {
@Override
public void method() {
System.out.println("pa~pa~pa:匿名内部类");
}
};
hero.setSkill(skill);
hero.attack();*/
//直接使用匿名内部类插入对象即可!
hero.setSkill(new Skill() {
@Override
public void method() {
System.out.println("Biu~biu~biu:直接调用无对象的匿名内部类。");
}
});
hero.attack();
}
}
显示效果:
我叫李云龙我释放了
Biubiubiu:直接调用无对象的匿名内部类。
打死了岗村宁次!