为类创建构造函数

时间:2015-03-04 07:53:11

标签: java constructor

我一直试图弄清楚这一点,似乎我不能在这堂课上称这只鹦鹉。

class Bird {
boolean f;
parrot Bird[];
int x;
}

我不能在Bird类中添加任何变量,我已经尝试将它放在构造函数中,但它下面总是有一条红线。

对我做错了什么的想法?

2 个答案:

答案 0 :(得分:1)

以这种方式改变你的课程:

class Bird {
    boolean f;
    Bird[] parrot;
    int x;
}

(您更改了类型的顺序和属性的名称)

答案 1 :(得分:-1)

您正在尝试创建自己的课程(我想,因为您没有提供有关Client课程的完整信息)。

然而,我认为问题是因为Bird课程中缺少构造函数。由于您没有在Bird类中声明任何构造函数,因此Java将自动从Object(这是包含其他所有内容的最大类)中获取默认构造函数。

要为您的Bird类创建构造函数,请执行以下操作:

class Animal {
    boolean f;
    Bird[ ] parrot;
    int x;

    public Animal() {
        this(false,inputParrot,inputX);
    }

    public Animal (boolean inputF, Bird[ ] inputParrot, int inputX) {
        f= inputF;
        parrot = new Bird[ ];
        parrot = inputParrot;
        x = inputX;
    }
}

我改变了你的班级名称,因为我假设你正在尝试创建一个Animal的树。因此,订单将是Animal有一个BirdBird有一个Parrot(如果您不确定,请研究has-a和is-a关系)。

相关问题