Java: Does this class code use a constructor?

I wrote the following code myself, but I am a little confused on the basics of "constructors". This code is supposed to get the radius of a circle and create a circle object and output info etc. etc. Basically the assignment was to use a constructor to accept the radius as an argument, but I'm not sure if that is what I have done? I am supposed to use a constructor to accept the radius and a setRadius mutator method.. but I feel like I've combined those... anyway I'm confused that's why looking for a bit of direction.

Here is the utility class:

public class Circle

{

public static final double PI = 3.14159;

private double r;

public void setRadius(double r) { this.r = r; }

public double getCircumference() { return 2 * PI * r; }

public double getArea() { return PI * r * r; }

public double getDiameter() {return r * 2; }

public double getRadius() { return r; }

}

Comments

  • Just make the constructor accept a double like your setRadius method, then call the setRadius method.

    public Circle(double x){

    setRadius(x);

    }

  • It's been a while since I took C++, which is similar to Java, but I'll try. The constructor is called when you create a new instance of the object, e.g. "new Circle foo(r)" or however the syntax goes. If I remember correctly, if you do not create an explicit constructor, then a default one is created for you, to instantiate the variables. I don't see a constructor here, and the only way to set the radius is by calling the setRadius method, which would have to be done after the "new" statement. I'm also not sure why you made PI public.

  • Your constructor has assignments backward: individual = call; score = identity; could desire to be: call = individual; score = identity; you additionally could make different constructors by using in simple terms specifying diverse arguments in a sparkling definition. After: public worker (String individual, int score) { ... } ... upload: public worker () { } public worker (String individual, int score, String branch, String place ) { ... } you additionally could have the constructors call one yet another. So the 4-arg one ought to call the two-arg one (looking after storing individual/score) so as which you basically could desire to complication approximately branch and place: public worker( String individual, int score, String branch, String place ) { this( individual, score ); branch = branch; place = place; }

Sign In or Register to comment.