140k views
1 vote
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.

User Lewkka
by
5.1k points

1 Answer

3 votes

Answer:

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.

User Lordjeb
by
5.4k points