42.2k views
5 votes
Consider the following class declaration: public class Square { private double sideLength; public double getArea() { return sideLength * sideLength; } public double getSideLength() { return sideLength; } } Assuming that a no-arg constructor already exists, write an overloaded constructor for this class. It should accept an argument that is copied into the sideLength field. The parameter’s name is s.

1 Answer

7 votes

Answer:

Here is the constructor:

public Square(double s) { //constructor name is same as class name

sideLength = s; } //s copied into sideLength field

Step-by-step explanation:

The above constructor is a parameterized constructor which takes a double type variable s as argument. The name of constructor is same as the name of class.This constructor requires one parameters. This means that all declarations of Square objects must pass one argument to the Square() constructor as constructor Square() is called based on the number and types of the arguments passed and the argument passed should be one and of type double.

Here is where the constructor fits:

public class Square {

private double sideLength;

public Square(double s) {

sideLength = s; }

public double getArea() {

return sideLength * sideLength;}

public double getSideLength() {

return sideLength; } }

User Goni
by
6.4k points