1

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?

2
  • 2
    Of course you can; it's just a method. Be wary of calling subclass methods, though. In any case, simply trying it would have almost certainly been faster. Commented Nov 11, 2014 at 16:06
  • 1
    This is the exact intent of constructors (and initialisation blocks) Commented Nov 11, 2014 at 16:10

2 Answers 2

1

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;
}
Sign up to request clarification or add additional context in comments.

2 Comments

Because that's not necessarily the only thing that setFillColor does. Not saying this is the case, but it may circumvent proper encapsulation.
fillColor is declared private within the constructor of GOval so that's not possible. And if I try to declare an instance variable myself within Ball with Color fillColor I get no errors but it also doesn't change the color. Too bad. However I got it working now!
1

Yes you can call other methods inside the constructor.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.