top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Why a static method can't use non-static data?

+1 vote
532 views
Why a static method can't use non-static data?
posted Jun 12, 2014 by Swati Arora

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

2 Answers

+1 vote

I will give u a example for this.

Let suppose, there is a class with a instance variable and static method

Class Example{

  int temp=5;
  public static void insert(){
  }
}

in this case we can access insert method in two ways
1) making a instance of example class then access insert method from that instance like,
Example e=new example();
e.insert();

2) access insert method directly by class name like,
Example.insert();

in second case we are not making a instance of Example class so memory will not allocated to variable temp. because variable temp is class level(instance) variable and class level variable will get memory only when object will be create.

That's why java don't allow us use of non static member in static method because in some cases(like case second) memory will not allocated to instance member.

answer Jun 17, 2014 by Anuj Agrawal
0 votes

Because it access only Static data. A Static Method can access Static Data because they both exist independently of specific instances of a class.

In most OO languages, when you define a method inside a class, it becomes an Instance Method. When you create a new instance of that class, via the new keyword, you initialize a new set of data unique to just that instance. The methods belonging to that instance can then work with the data you defined on it.

Static Methods, by contrast, are ignorant of individual class instances. The static method is similar to a free function in C or C++. It isn't tied to a specific instantiation of the class. This is why they cannot access instance values. There's no instance to take a value from!

Static Data is similar to a static method. A value that is declared static has no associated instance. It exists for every instance, and is only declared in a single place in memory. If it ever gets changed, it will change for every instance of that class.

answer Jun 13, 2014 by Aastha Joshi
...