-4

I wonder if a constructor in Java can look like this:

public double[] values;

I'm not sure if the constructor can look like this, or should it be

public values (double[] values){
    values = someValues;
}
  • 1
    Neither of those are valid constructors in this case. The first is a valid field declaration, where public is the access modifier, double[] is the type, and values is the name of the field. For the second, I don't believe that will compile. it looks like your classname is values, but you also have values as the methods parameter double[] values. I think I'm a little confused as to what you're looking to do, are you looking to take in a double[] in the constructor and set a local field to those values? – JosephRT May 9 '18 at 2:03
  • It's not clear what you're actually trying to achieve with these constructors. What is the problem you are trying to solve? – Sean Burton May 9 '18 at 16:15
2

Nope. This

public double[] values;

just declares a public array of doubles named values.

And this

public values (double[] values){
    values = someValues;
}

fails even when properly indented. It still isn't right because you didn't define the class name. Even if you did declare values inside a class named values you still messed up. Because while it might work as a constructor in this

class values {    
    public double[] values;

    public values (double[] values){
        values = someValues;
    }
}

values is a horrible name for a class. Bleh. Capitalize class names, don't plurize them, and for pete sake make them more descriptive than values. Oh and you never defined someValues.

To see what forms are and are not allowed as constructors I encourage you to look at the Java specification for them.

ConstructorDeclaration:
{ConstructorModifier} ConstructorDeclarator [Throws] ConstructorBody

ConstructorDeclarator:
[TypeParameters] SimpleTypeName ( [FormalParameterList] )

SimpleTypeName:
Identifier

It gives this example:

class Point {
    int x, y;
    Point(int x, int y) { this.x = x; this.y = y; }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.