Ask Question

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.

+1
Answers (1)
  1. 2 August, 22:07
    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?
Find 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 the answers seem to be not correct or there’s no answer. Try a smart search to find answers to similar questions.
Search for Other Answers