我是 Java 的新手(我正在学习 AP 计算机科学),我的书 Big Java 提出了这个问题:
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.
我敢肯定,对于更有经验的编码人员来说,答案是显而易见的,但我真的不确定为什么将 area 设为实例变量是一种糟糕的方法。任何指导将不胜感激!
最佳答案
面积是根据边长计算的值。实例变量保存对象的状态,如果您将它包含在那里,您将不得不维护两个冗余状态。
将 area 包含为实例变量将被视为缓存,因为您保存了结果而不是重新计算。这有时是需要的,但在这里不是因为计算足够便宜。
关于java - 为什么不是实例变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39474656/