JAVA课堂作业实现家谱(调用每个人要说一句话)

JAVA课堂作业,本人才上了一节课就要做了,需要用JAVA实现家谱,求大神援手【泪目】

img

代码如下:
(1)新建一个Person类


public class Person {
    
    protected String name;
    protected int age;
    protected Person father;
    protected Person mother;
    protected Person[] child;
    
    Person(){
        father = null;
        mother = null;
        child = null;
    }
    
    
    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 Person getFather() {
        return father;
    }
    public void setFather(Person father) {
        this.father = father;
    }
    public Person getMother() {
        return mother;
    }
    public void setMother(Person mother) {
        this.mother = mother;
    }
    public Person[] getChild() {
        return child;
    }
    public void setChild(Person[] child) {
        this.child = new Person[child.length];
        for(int i = 0;i<child.length;i++){
            this.child[i] = child[i];
        }
    }
    
    
    public void Said(){
        System.out.print("我的名字是" + name );
        if(father != null)
            System.out.print(",我的父亲是" + father.getName());
        if(mother != null)
            System.out.print(",母亲是"+mother.getName());
        
        if(this.child != null){
            if(this.child.length > 0){
                System.out.print(",我有" + this.child.length + "个孩子。");
                System.out.print("分别是:");
                for(int i = 0;i<this.child.length; i++)
                    System.out.print(" " + this.child[i].getName());
            }
        }else
                System.out.print(",我没有孩子");
        
        System.out.println();
    }

}


(2)添加一个测试类:


public class TestWork {
    public static void main(String[] args){
        Person p1 = new Person();
        p1.setName("张翠山");
        p1.setAge(56);
        Person p2 = new Person();
        p2.setName("殷素素");
        p2.setAge(54);
        Person p3 = new Person();
        p3.setName("张无忌");
        p3.setAge(28);
        
        Person p4 = new Person();
        p4.setName("无名氏");
        p4.setAge(22);
        
        Person[] ch = new Person[2];
        ch[0] = p3;
        ch[1] = p4;
        
        p1.setChild(ch);
        p2.setChild(ch);
        
        p3.setFather(p1);
        p3.setMother(p2);
        
        p4.setFather(p1);
        p4.setMother(p2);

        
        p1.Said();
        p2.Said();
        p3.Said();
        p4.Said();
        
    }

}


在无参构造器中打印台词即可,创建对象的时候会打印出来。

这个说的就是继承和迭代,
不知道你目前遇到的问题是什么?

如需交流,欢迎。