类作为成员变量类型
定义一个武器类
public class weapon {
private String weaponName;
public weapon() {
}
public weapon(String weaponName) {
this.weaponName = weaponName;
}
public String getWeaponName() {
return weaponName;
}
public void setWeaponName(String weaponName) {
this.weaponName = weaponName;
}
}
定义一个英雄类,其中用武器类作为成员变量的类型
public class Hero {
private String name;
private int age;
private weapon wea;
public Hero() {
}
public Hero(String name, int age, weapon wea) {
this.name = name;
this.age = age;
this.wea = wea;
}
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 weapon getWea() {
return wea;
}
public void setWea(weapon wea) {
this.wea = wea;
}
}
使用
public class Game{
public static void main(String[] args) {
Hero one = new Hero();
one.setAge(13);
one.setName("吕布");
weapon wea1 = new weapon("方天画戟");
one.setWea(wea1);
}
}
接口作为成员变量类型
定义接口
public interface Skill {
void skill();
}
定义英雄,使用接口作为成员变量类型
public class Hero {
private String name;
private int age;
private weapon wea;
private Skill skill;
public Hero() {
}
public Hero(String name, int age, weapon wea) {
this.name = name;
this.age = age;
this.wea = wea;
}
public Skill getSkill() {
return skill;
}
public void setSkill(Skill skill) {
this.skill = skill;
}
public Hero(Skill skill) {
this.skill = skill;
}
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 weapon getWea() {
return wea;
}
public void setWea(weapon wea) {
this.wea = wea;
}
}
使用
public class Game{
public static void main(String[] args) {
Hero one = new Hero();
one.setAge(13);
one.setName("吕布");
weapon wea1 = new weapon("方天画戟");
one.setWea(wea1);
创建匿名内部类
Skill ski = new Skill() {
@Override
public void skill() {
System.out.println("释放技能");
}
};
one.setSkill(ski);
}
}