Ask Question
22 November, 12:35

Consider the following implementation of a class Square:

public class Square

{

Private int sideLength;

Private int area; / / Not a good idea

public Square (int length) {

sideLength = length;

}

Public int getArea () {

area = sideLength * sideLength;

return area;

}

}

Why is it not a good idea to introduce an instance variable for the area? Rewrite the class so that area is a local variable.

+2
Answers (1)
  1. 22 November, 16:21
    0
    The answer to this question can be given as:

    Code:

    class Square / /define class Square

    {

    Private int sideLength; / /define variable

    Square (int length) / /define parameterized constructor.

    {

    sideLength = length; / /hold value of the parameter

    }

    int getArea () / /define function getArea.

    {

    Private int area; / /define variable.

    area = sideLength * sideLength; / /calculate area.

    return area; / /return value.

    }

    }

    Explanation:

    In this question it is not a good idea to introduce an instance variable for the area because It may be a different method that defines the same variable with the same name but different variables because they are related to different functions, so it is better to make this variable local in this case.
Know the Answer?
Not Sure About the Answer?
Get an answer to your question ✅ “Consider the following implementation of a class Square: public class Square { Private int sideLength; Private int area; / / Not a good ...” in 📙 Computers & Technology if there is no answer or all answers are wrong, use a search bar and try to find the answer among similar questions.
Search for Other Answers