Joop
Joop

Reputation: 3788

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?

Upvotes: 1

Views: 71

Answers (2)

Mahesh Acharya
Mahesh Acharya

Reputation: 11

Yes you can call other methods inside the constructor.

Upvotes: 1

usha
usha

Reputation: 29349

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;
}

Upvotes: 1

Related Questions