Quinton Ships Quinton Ships - 1 year ago 69
Java Question

Why not instance variable?

I'm relatively new to Java (I'm taking AP computer science) and the book I have, Big Java, poses this 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.

I'm sure the answer is obvious to a more experienced coder but I'm really unsure why making area an instance variable is a bad approach. Any guidance would be much appreciated!

Answer Source

I am not sure what (else) the author meant to say by that, one thing that I come up with is that it would just take up extra and redundant space in the memory each time you instantiate the object. Whereas you can write the simple method body as,

public int getArea() {
    return sideLength * sideLength;

This way, you don't take up any extra space in the memory, you send the calculation to CPU and get the results. Which is a good approach in real-world applications. For beginners, understanding the creation of variables, type-matching etc would be simpler to understand. Nothing else.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download