
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Access Instance Variables from a Static Method in Java
We cannot directly access the instance variables within a static method because a static method can only access static variables or static methods.
An instance variable, as the name suggests is tied to an instance of a class. Therefore, accessing it directly from a static method, which is not tied to any specific instance doesn't make sense. Therefore, to access an instance variable, we must have an instance of the class from which we access the instance variable.
Example:
public class Test { public int instanceVariable = 10; public static void main(String args[]) { Test test = new Test(); System.out.println(test.instanceVariable); } }
Output:
10
Advertisements