"Can a non-static method access a static variable or call a static method" is one of the frequently asked questions on the 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 belong 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 like main() can be called from anywhere.
Btw, if you are new to Java world then I also suggest you go through a comprehensive Java course like The Complete Java Masterclass on Udemy which covers both OOP and Java. It is also one of the affordable courses and most up-to-date. It covers new Java features introduced in recent Java releases.
Here is a code example to prove our point that a non-static method can access both static variables and methods in Java.
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 is absolutely beautiful.
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 problem is a little bit tricky and often asked confused candidates because the opposite is not exact, 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.
As I said before, your 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 non-static member variables or methods cannot be accessed from a static method in Java:
$ 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 exact. 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 you can access a non-static variable or call a non-static method from a static method like the main() method in Java? Let's find out.
$ 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 non-static variables/methods from a static context, like a static initializer block, static method, or a nested static class in Java. See The Complete Java Masterclass course on Coursera for more details.
That's all about whether a non-static method can access a static variable or method in Java or not. Of course, they can, but the opposite is not true, i.e. you cannot obtain 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 to.
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 on static concepts on OCAJP, particularly on the Whizlabs Java 8 Exam Simulator; hence, it is essential to prepare this topic well.
Other related Java articles from Javarevisited blog:
P. S. - If you are preparing for Java certification and want to prepare this topic well than reading a good core Java course like Oracle Java Certification - Pass The Java 11 SE Exam can also help a lot. This is an excellent course to learn core Java fundamentals even if you are not preparing for exams.
Similarly, a private static method can be called from a non-static method of the same class but a public static method like main() can be called from anywhere.
Btw, if you are new to Java world then I also suggest you go through a comprehensive Java course like The Complete Java Masterclass on Udemy which covers both OOP and Java. It is also one of the affordable courses and most up-to-date. It covers new Java features introduced in recent Java releases.
Here is a code example to prove our point that a non-static method can access both static variables and methods 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 is absolutely beautiful.
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 problem is a little bit tricky and often asked confused candidates because the opposite is not exact, 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.
As I said before, your 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 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); } }
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 exact. 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 you can access a non-static variable or call a non-static method from a static method like the main() method in Java? Let's find out.
How to access a non-static variable/method from a 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 non-static variables/methods from a static context, like a static initializer block, static method, or a nested static class in Java. See The Complete Java Masterclass course on Coursera for more details.
That's all about whether a non-static method can access a static variable or method in Java or not. Of course, they can, but the opposite is not true, i.e. you cannot obtain 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 to.
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 on static concepts on OCAJP, particularly on the Whizlabs Java 8 Exam Simulator; hence, it is essential to prepare this topic well.
Other related Java articles from Javarevisited blog:
- Can abstract class have a constructor in Java? (answer)
- Top 10 Courses to learn Java in-depth (courses)
- Can you overload or override static method in Java? (answer)
- My favorite free courses to learn Java (courses)
- Can we declare a class static in Java? (answer)
- 10 Advance Java courses for experienced developers( courses)
- Can you make an array volatile in Java? (answer)
- 10 Advanced Java books for experienced programmers (books)
- 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)
- Top 5 Free Java 8 and Java 9 courses for Programmers (courses)
- 5 Free courses to learn object-oriented programming in Java (courses)
- 10 Must Read books to learn Java in-depth (books)
- 50+ Java Interview Questions for beginners (interview questions)
P. S. - If you are preparing for Java certification and want to prepare this topic well than reading a good core Java course like Oracle Java Certification - Pass The Java 11 SE Exam can also help a lot. This is an excellent course to learn core Java fundamentals even if you are not preparing for exams.
Good Explanation man.
ReplyDeleteThanks @Rabbani
ReplyDeletegot it
ReplyDelete