Question #47304

Consider the following implementation of a class Square:

public class Square
{
privateintsideLength;
privateint area; // Not a good idea

public Square(int length){
sideLength = length;
}
publicintgetArea(){
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.

Expert's answer

Answer on Question #47304, Programming, Other

Task:

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.

Answer:

It is not a good idea to introduce an instance variable for the area because it may be another method, which defines the same variable that has the same name but are different variables, since they are linked with different functions, so in this case it is better to make this variable local.


public class Square
{
Private int sideLength;
public Square(int length){
sideLength = length;
}
Public int getArea(){
Private int area;
area = sideLength * sideLength;
return area;
}
}


http://www.AssignmentExpert.com/

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

LATEST TUTORIALS
APPROVED BY CLIENTS