永发信息网

Java如何设置2个对象的关系

答案:1  悬赏:20  手机版
解决时间 2021-03-05 11:50
比如我新建了Student类,定义了2个成员变量,String Name,boolean GuanXi。
那我可以新建2个对象, Student a和Student b,当a.GuanXi&&b.GuanXi为true时,两者为同学。

private String Name;
private boolean GuanXi_1;

public void Student(Straing Name, boolean GuanXi_1){
this.Name = Name;
this.GuanXi_1 = true;
}

public static void main(String[] args){
Student a = new Student("小明", true);
Student b = new Student("小张", true);

if(a.GuanXi_1&&b.GuanXi_1){
System.out.println(a.name +"和" b.name + "是同学");
}else{
System.out.println(a.name +"和" b.name + "不是同学");
}
}

我想问的是,能不能写一个新的参数,或者新的方法,或者新的类,直接设置a和b是同学?
比如通过这样设置。
a.xinGuanXi(b,TongXue);
然后,每次我想知道a和b的关系,只需要使用如下方法,就可以显示出a和b的关系。
a.GunXi(b);
控制台就会显示"a和b是同学"或"a和b不是同学"。
最佳答案
public class Student {
    private String name;
    private List<Student> classmates = new ArrayList<>();


    public Student(String name){
        this.name = name;
    }

    public void isClassmate(Student student){
        this.classmates.add(student);
    }

    public boolean guanXi(Student s){
        if(this.classmates.contains(s)){
            System.out.println(this.name+"和"+s.name+"是同学");
            return true;
        }else {
            System.out.println(this.name+"和"+s.name+"不是同学");
            return false;
        }
    }

    public static void main(String[] args) {
        Student a = new Student("小明");
        Student b = new Student("小张");
        a.isClassmate(b);
        b.isClassmate(a);
        a.guanXi(b);

        Student c = new Student("小红");
        a.guanXi(c);
    }
}main执行结果:
小明和小张是同学
小明和小红不是同学
我要举报
如以上问答信息为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
笔记本屏幕UHD和FHD哪个好?
下列动物,不营群体生活的是 A蚂蚁 B.大熊猫
帝富龙卫浴在哪里啊,我有事要去这个地方
只有鸡蛋怎么做汤
形容做事认真细致,一点儿不马虎的四字词语是
2+□×6的得数是多少
设4阶方阵A通过列分块后为(a1,a2,a3,a4) b
乡巴佬卤肉我想知道这个在什么地方
香港富誉卤鸭馆在哪里啊,我有事要去这个地方
如何区别"北北、京京、欢欢、迎迎、昵昵"这五
兰花叶尖焦尖是怎么回事
【国旗下的演讲稿】高中生新学期国旗下讲话稿
好客地址有知道的么?有点事想过去
负重用铅块与钢板哪个好?
团风县黄冈纯粮酒坊地址在哪里啊
推荐资讯
找一句鼬的日文翻译:
50港币等于多少人民币2016年
女中学生什么发型好看
屯溪区黄山迎宾超市我想知道这个在什么地方
驾驶证丢了可以委托别人办吗
高山红景天与松花粉对比哪个更好
盐都区潘黄镇重大动物疫病防治领导小组办公室
我刚吃了10多个杏仁没事吧?
伟大的俄罗斯作家列夫.托尔斯泰在青年时期曾
简爱鲜花连锁(花满缘鲜花)地址有知道的么?有
【60万5千1百,英文怎么说= =汗RT~THX】
吉山英君路在哪里啊,我有事要去这个地方
正方形一边上任一点到这个正方形两条对角线的
阴历怎么看 ?