tags:

views:

76

answers:

3
Case:1

    class A
    {
        private int i=0;

        public void display()
        {
            this.getValue();
        }

        private int getValue()
        {
            return i+2;
        }

    }

Case:2

    class B
    {
        public void display()
        {
            int i=0;
            this. getValue(i);
        }

        private int getValue(int i)
        {
            return i+2;
        }
    }

Does the declaration of "i" in both cases have any great difference (other than the global access) whenever I call display() ?

+2  A: 

In this very case the effect is the same, but an instance of the class in the first snippet will occupy more memory.

Other than that in the first case it's a variable with the same address on each call and it retains the value, but in the second case it's not necessarily a variable with the same address - it is reallocated and reinitialized on each call.

Since you actually don't ever change i variable value you should declare it as const - this will give more clear code.

sharptooth
Except if this is Java, where `const` does not exist.
Jesper
Isn't `final` for the same in Java?
sharptooth
A: 

In first case i exists outside of any method

In second case i exists only when display() method is called. If you want to give it persistence you can declare it as static.

mouviciel
Except if this is Java, where local static variables don't exist.
Jesper
+1  A: 

In first case i is a part of the object. When u create an object from class A, the object allocates memory for the variable "i". And it will remain until the object deleted.

But in the second way when you create the object from class B, there will be no memory allocation for the variable i. But only when you call the display function -in class B- memory variable "i" will be allocated temporarily. (When function's work is done all local variables will free)

H2O