简体   繁体   English

创建构造函数时,可以在对象上调用方法吗?

[英]Can you invoke a method on an object in creation of a constructor?

I created a subclass named Ball of GOval. 我创建了一个名为GOval的子类。 I would like to create a black ball. 我想制造一个黑球。 In order for this to work I tried this: 为了使它起作用,我尝试了以下方法:

Within a class I create a new Ball object. 在一个类中,我创建一个新的Ball对象。

Ball ball = new Ball(0,0,200);

This invokes this constructor in Ball (which extends GOval) 这将在Ball中调用此构造函数(扩展了GOval)

public Ball(double xPos, double yPos, double diameter){
    super(xPos, yPos, diameter, diameter);
}

I would like also initialise the color as well as set the color filled within this constructor. 我还要初始化颜色以及设置此构造函数中填充的颜色。 The problem is that these are methods you invoke on an object. 问题是这些是您在对象上调用的方法。 For instance this works: 例如,这有效:

Ball ball = new Ball(0,0,200);
ball.setFillColor(Color.BLACK)
add(playball);

But what I really want is do these last two instructions in the construction in the ball class like this: 但是我真正想要的是在球类的构造中执行以下最后两个指令:

public Ball(double xPos, double yPos, double diameter){
        super(xPos, yPos, diameter, diameter);
        setFillColor(Color.BLACK);
    }

Thank you for your replies: I got it working with: 谢谢您的回覆:我让它与以下人员合作:

setFilled(true);
setColor(Color.BLACK);

This probably works because I call the constructor of GOval with super, and then I call these methods (setFilled and setColor) on that object? 之所以可行,是因为我用super调用了GOval的构造函数,然后又对该对象调用了这些方法(setFilled和setColor)?

Since fillColor is an attribute on Ball class, why can't you set it directly instead of calling the method 由于fillColor是Ball类的属性,所以为什么不能直接设置它而不是调用方法

public Ball(double xPos, double yPos, double diameter){
    super(xPos, yPos, diameter, diameter);
    this.fillColor = Color.BLACK;
}

是的,您可以在构造函数中调用其他方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM