可以批准参数的类定义 - 使用对象和构造函数

时间:2012-11-11 20:22:00

标签: java class object constructor

我必须创建类定义,它可以批准在构造函数被引入时该对象已经存在的参数。

我不知道如何解释这个问题,我已经尝试过这样的事情,但这是错误的:

public class B {

  int obj;

  public B() {  

  }

    public static void main(String[] args) {

    B object = new B();
    System.out.println(object)

    }
}

我写的代码来自第一个练习:

public class Bulb {

static int a;

public Bulb(int ab) {
    a = ab;
}


public static void main(String[] args) {

    Bulb object = new Bulb(a);
    System.out.println(object);

}

它有一个参数构造函数。

1 个答案:

答案 0 :(得分:1)

在我们的长评论帖之后,听起来我们已经确定你所做的是学习继承和多态。您指定的B类必须继承Bulb,并且您必须首先在B的构造函数之前证明Bulb的构造函数被调用。我不确定是否有比使用日志输出更好的方法。除扩展和记录器消息外,您的代码几乎包含您需要的所有内容。你可以这样做:

public class Bulb{
    int ab;
    public Bulb(int ab){
        this.ab = ab;
        System.out.println("Bulb constructor is invoked");
    }

    // The rest of your Bulb class
}

在B类中,扩展了Bulb:

public class B extends Bulb{
    public B(int ab){
        // Call the super constructor, which in this case is the Bulb constructor
        super(ab);
        System.out.println("B constructor is invoked");
    }
    // The rest of your B class
}

这有意义吗?

编辑: 我忘了提到:在Java中,当你有一个继承结构时,总是从上到下调用​​构造函数。这意味着,您的层次结构中最顶级的类首先被调用(在这种情况下,它将是Bulb),然后向下逐渐调用(例如,您的B类)。