Can a non static method access static variable/method in Java?

"Can a non-static method access a static variable or call a static method" is one of the frequently asked questions on static modifier in Java, the answer is, Yes, a non-static method can access a static variable or call a static method in Java. There is no problem with that because of static members i.e. both static variable and static methods belongs to a class and can be called from anywhere, depending upon their access modifier. For example, if a static variable is private then it can only be accessed from the class itself, but you can access a public static variable from anywhere. Similarly, a private static method can be called from a non-static method of the same class but a public static method e.g. main() can be called from anywhere.

Here is a code example to prove our point that a non-static method can access both static variable and method in Java:

public class StaticTest {

  public static int iStatic = 10;

  public void nonStatic() {
    System.out.println("can access static variable inside non-static method : "
        + iStatic);
    main(new String[2]);
  }

  public static void main(String[] args) {
    System.out.println("Inside main method");
  }

}

You can see that this code compiles just fine, there is no compile time error. You can even access a nested static class from a non-static method, it absolutely fine.


But, just think, If the answer is that simple, then why this question is frequently asked on Java interviews and Java certifications like OCAJP or OCPJP? Well, the question is a little bit tricky and often asked confused candidates because the opposite is not true i.e. you can access static members from non-static context but you cannot access a non-static variable or method from a static method in Java.

Why you cannot access a non-static variable or call a non-static method from a static method in Java? Well, this is because a static method forms a static context where only static members can be accessed, but if you want more explanation, I suggest you go through one of the more comprehensive resources like Core Java Fundamentals course from Pluralsight by Jim Wilson.

Can a non static method access static variable/method in java?


As I said before, the code is the best documentation. Try to prove the point by writing code and that's what we'll do it here. Following is a code example to prove above point that a non-static member variables or methods cannot be accessed from a static method in Java:

class Hello {
  private static int aStaticVariable = 1;
  private int aNonStaticVariable = 2;

  private static void aStaticMethod() {
    System.out.println(aNonStaticVariable);
    aNonStaticMethod();
  }

  private void aNonStaticMethod() {
    System.out.println(aStaticVariable);
  }

}

$ javac Hello.java
Hello.java:11: non-static variable aNonStaticVariable cannot be referenced from a static context
System.out.println(aNonStaticVariable);
^
Hello.java:12: non-static method aNonStaticMethod() cannot be referenced from a static context
aNonStaticMethod();
^
2 errors


You can see that even though you can access static members from a non-static method, the opposite is not true. If you try to access a non-static variable or method or even a nested class, the compiler will throw error "non-static method XXXX cannot be referenced from a static context".

So, now the big question comes how can you access a non-static variable or call a non-static method from a static method e.g. main() method in Java? let's find out.



How to access a non-static variable/method from static method in Java

Well, there is a legitimate way to access any non-static member from the static context in Java, by creating instances. You need to first create an object of the class whose non-static members or non-static method you want to access. Once you do that, the compiler will not bother you anymore as shown in the following example:

public class Hello {

  private static int aStaticVariable = 1;
  private int aNonStaticVariable = 2;

  private static void aStaticMethod() {
    Hello object = new Hello();
    System.out.println(object.aNonStaticVariable);
    object.aNonStaticMethod();
  }

  private void aNonStaticMethod() {
    System.out.println(aStaticVariable);
  }

}

$ javac Hello.java

You can see that all compile-time error has gone after access non-static variable and method using an object of the Hello class. This is the right way to access a non-static variables/methods from a static context e.g. a static initializer block, static method, or a nested static class in Java. See Java: The Core Platform for more details.


That's all about whether a non-static method can access static variable or method in Java or not. Of course, they can but the opposite is not true i.e. you cannot access a non-static member from a static context i.e. static method. The only way to access a non-static variable from a static method is by creating an object of the class the variable belongs.

This confusion is the main reason why you see this question on core Java interview as well as on core Java certifications e.g. OCAJP and OCPJP exam. You will find a lot of questions based upon static concepts on OCAJP, hence it is very important to prepare this topic well by reading a good core Java book e.g. OCAJP Study Guide by Mala Gupta. This is an excellent book to learn core Java fundamentals even if you are not preparing for exams.


Further Learning
Java Fundamentals Part 1 and 2
Head First Java 2nd Edition
Whizlabs Java 8 Exam Simulator


Other related Java articles from Javarevisited blog:
Can abstract class have a constructor in Java? (answer)
Can you overload or override static method in Java? (answer)
Can we declare a class static in Java? (answer)
Can you make an array volatile in Java? (answer)
Can you run a Java program without main() method in Java? (answer)
Can you make an abstract class final in Java? (answer)
Can you override a private method in Java? (answer)

Thanks for reading this article, if you like this article then please share with your friends and colleagues. If you have any questions or feedback then please drop a comment. 

No comments :

Post a Comment