Search This Blog

Thursday 15 November 2012

Why non static variable are not allow to use in static method in Java?

Most common thing about static variable we know, static means no need to create a instance. static variable can used with out instantiating class. Another fact about static variable is, we can not use non static variable inside a static method. if we forcefully go against it and use non static variable inside a static method then we get compile time error

      "Cannot make a static reference to the non-static field rectArea"   

Why it so ? why Java keeps such restriction? 

Compile this code -   

public class A {

 private static float rectArea;

 public static void main(String[] args) {
  A one = new A();
  A two = new A();
  A three = new A();
  System.out.print("Print Area = " + rectArea);

 public void setArea(float areap) {
  rectArea = areap;

This indicate a compile time error. So for a moment just ignore the error and let analyze our main issue. A class has instantiated three times. Variable rectArea has value corresponding to each instance.

  Lets go to System.out.print("Print Area = " + rectArea). 

We know we can access static variable without creating object, means static variable value does not depends on object of a class. Same things applied to methods.   So when we are trying to access rectArea which value depends on object of class A (as rectArea is not a static variable), it gives error. Because compiler get confused which value to use 200,300,or 400 for rectArea.  To avoiding this issue Java restrict that we can not use non static variable inside a static method. Same applies when you try to use non static method inside a static method 

No comments:

Post a Comment

Feedback always help in improvement. If you have any query suggestion feel free to comment and Keep visiting my blog to encourage me to blogging

Android News and source code