类作为成员变量类型
package test;
public class Weapon {
private String code;//武器的代号
public Weapon() {
}
public Weapon(String code) {
this.code = code;
}
//省略Getter/Setter方法
package test;
public class Hero {
private String name;//英雄的姓名
private int age;//英雄的年龄
private Weapon weapon;//英雄的武器
public Hero() {
}
public Hero(String name, int age, Weapon weapon) {
this.name = name;
this.age = age;
this.weapon = weapon;
}
public void attack(){
System.out.println("年龄为"+getAge()+"的"+getName()+"拿着"+weapon.getCode()+"在推塔");
}
//省略Getter/Setter方法
package test;
public class DemoMain {
public static void main(String[] args) {
Hero hero = new Hero();//创建英雄
hero.setName("伦伦");//设置名字
hero.setAge(23);//设置年龄
//创建武器对象并设置代号
Weapon weapon=new Weapon("大宝剑");
// hero.setWeapon(new Weapon("大宝剑"));
hero.setWeapon(weapon);//为英雄配备武器
hero.attack();//年龄为23的伦伦拿着大宝剑在推塔
}
}
接口作为成员变量类型
public interface Skill {
void use();//释放技能的抽象方法
}
package test;
public class Hero {
private String name;//英雄的名称
private Skill skill;//英雄的技能
public Hero() {
}
public void attack(){
System.out.println("我叫"+getName());
skill.use();
}
public Hero(String name, Skill skill) {
this.name = name;
this.skill = skill;
}
public Hero(String name) {
this.name = name;
}
//省略Getter/Setter方法
}
package test;
public class DemoGame {
public static void main(String[] args) {
Hero hero = new Hero("艾希");
//hero.setSkill(new SkillImpl());需要创建接口实现类
//改成使用匿名内部类
/*Skill skill=new Skill() {
@Override
public void use() {
System.out.println("射箭");
}
};
hero.setSkill(skill);*/
//进一步简化,同时使用匿名内部类和匿名对象
hero.setSkill(new Skill() {
@Override
public void use() {
System.out.println("射箭");
}
});
hero.attack();
}
}
接口作为方法的参数
package test.param;
import java.util.*;
public class Demo01 {
public static void main(String[] args) {
//左边是接口,右边是实现类名称
ArrayList<String> list=new ArrayList<>();
List<String> res = addNames(list);
for (String re : res) {
System.out.println(re);
}
}
public static List<String> addNames(List<String> list){
list.add("张三");
list.add("李四");
list.add("王五");
return list;
}
}
/*张三
李四
王五*/