Pratik Paul
Pratik Paul

Reputation: 93

why not declare every variables as Static

I am new to Java and recently I have studied about static variables. I got to know that for a static variable memory is allocated only once. This means that it will save a lot of memory.My question is that if static variables saves memory, why not declare every variable as static. This will save a lot of memory while creating an application. Pardon me if this seems a silly question, but actually I am just a bit curious.

Upvotes: 2

Views: 569

Answers (4)

Sonal
Sonal

Reputation: 679

Yes, it would be allocated memory once in the life cycle and is known as class variable. A class variable can be accessed directly with the class, without the need to create an instance. This would mean that it can be accessed from anywhere and everywhere. Also, memory allocation would mean that even if the variable is not used at many places in the code it would stay in the memory forever as long as the program is running and would take up unnecessary space.

Upvotes: 0

Jor El
Jor El

Reputation: 199

Static variable are created per class level. It is not created when an Object of the class is created. For every instance or object of the class there is only one value of a static member variable. This defeats the purpose of having objects and creating an application around objects.

Upvotes: 0

ka4eli
ka4eli

Reputation: 5424

It's the basics of OOP. Look at an example:

class Person {
    public String name = "Foo";
}

Field name is not static, it means that objects of class Person will not share it and each person will have it's own name. And when you change one's person name others will stay unaffected. But if you make it static:

class Person {
    public static String name = "Foo";
}

It means, that all persons share the same name which is kind of strange, do you agree?)

Upvotes: 1

CarlosMorente
CarlosMorente

Reputation: 918

The point on creating attributes/variables is that you'll want them as a "feature" for the object. For example, if you have a class "Car", maybe you'll want a variable to reference the color of the car.

The problem is that every instance of "Car" (in real world it'll be each different car) has a value, so each has to be an "independent" variable.

You can use static variables for those ones that are shared by all the objects of this class. For example, a counter to determine how many cars are there. This variable belongs to the class called "Car", but not to any specific instance of that class.

Upvotes: 0

Related Questions