简体   繁体   中英

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

I created a subclass named Ball of 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 = new Ball(0,0,200);

This invokes this constructor in Ball (which extends 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?

Since fillColor is an attribute on Ball class, why can't you set it directly instead of calling the method

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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