兩個(gè)對(duì)象之間的一對(duì)一關(guān)系如何表示这刷?
比如:一個(gè)英雄(hero)對(duì)一個(gè)兵器(weapon)
/**兩個(gè)對(duì)象的一對(duì)一關(guān)系:
比如一個(gè)英雄(hero)對(duì)一個(gè)兵器(weapon)
雙向一對(duì)一
單向一對(duì)一
*/
import java.util.*;
public class Main{
public static void main(String[] args){
Hero hero=new Hero("劉備",50);
Weapon weapon=new Weapon("雙股劍",3);
//把兩個(gè)對(duì)象關(guān)聯(lián)起來(lái);
hero.setWeapon(weapon);
weapon.setHero(hero);
//通過(guò)英雄來(lái)獲取他的信息娩井;
String name=hero.getName();
int age=hero.getAge();
Weapon w=hero.getWeapon();
System.out.println("我是"+name+"暇屋,我"+age+"歲,"+"我的兵器是:"+w.getName()+"洞辣,兵器等級(jí)為:"+w.getGrade()+"級(jí)");
}
}
//英雄類
class Hero{
private String name;
private int age;
private Weapon weapon;//一對(duì)一關(guān)系
public void setWeapon(Weapon weapon){
this.weapon=weapon;
}
public Weapon getWeapon(){
return weapon;
}
public Hero(){}
public Hero(String name,int age){
this.name=name;
this.age=age;
}
public void setName(String name){
this.name=name;
}
public void setAge(int age){
this.age=age;
}
public String getName(){
return name;
}
public int getAge(){
return age;
}
}
//兵器類
class Weapon{
private String name;
private int grade; //兵器等級(jí)
private Hero hero;
public void setHero(Hero hero){
this.hero=hero;
}
public Hero getHero(){
return hero;
}
public Weapon(){}
public Weapon(String name,int grade){
this.name=name;
this.grade=grade;
}
public void setName(String name){
this.name=name;
}
public void setAge(int grade){
this.grade=grade;
}
public String getName(){
return name;
}
public int getGrade(){
return grade;
}
}