kavi temre
kavi temre

Reputation: 1321

Why did the Java designer restrict the use of non-static variable in static context?

I know that non-static variables cannot be referenced from a static context. I want to know why the Java designer made this restriction.

I have checked Stack Overflow, and there are so many similar questions and answers, but I want to know the exact reason.

Upvotes: 1

Views: 76

Answers (2)

Kevin J. Chase
Kevin J. Chase

Reputation: 3956

This is like asking why the universe restricts you from breathing in deep lungfuls of air in outer space. It's impossible because the vacuum of space is defined by the absence of air, not because some designer chose to prevent you.

Likewise, in a static context there are no non-static variables. (It's right there in the name.) You can't refer to a non-static variable in static context any more than you could read a book that hasn't been written.

Upvotes: 1

Lubed Up Slug
Lubed Up Slug

Reputation: 178

So a non-static variable means that an object is required for that variable to have a value. So for example if you have a Car class and you have the non-static variable price it wouldn't make sense that price can be simply referenced by Car.price. That would be like if I asked you "What is the price of a car?". You would tell me that it varies. It would be logical that different cars would be different prices. So if I make a Car BMW then its price would be different than the Car Honda. Now why would you have a static variable? Well if you have something that is true for all cars like say the tax on them. It could also be something you would want to know without having a car, like say the description of what a car is. That doesn't mean that it can't be changed it just means that is same for all instances of that class.

Upvotes: 6

Related Questions