How does a static method access instance variables?
Static methods can not directly access any instance variables or methods. But they can access them by using their object reference. Static methods may even access private instance variables via a object reference.
public class Program {
private int count;
public Program(int ballcount){
count=ballcount;
}
public static void main(String argv[]){
Program s = new Program(99);
//System.out.println(count); //compile time error
//add(10); //compile time error
System.out.println(s.count);
s.add(10);
System.out.println(s.count);
}
private void add(int num) {
count += num;
}
}
The output result is
99
109
All private instance variables are private to its class, they can be accessed by static methods or non-static method of the class.
Most Recent java Faqs
- How to uncompress a file in the gzip format?
- How to make a gzip file in Java?
- How to use Java String.split method to split a string by dot?
- How to validate URL in Java?
- How to schedule a job in Java?
- How to return the content in the correct encoding from a servlet?
- What is the difference between JDK and JRE?
Most Viewed java Faqs
- How to read input from console (keyboard) in Java?
- What are class variables in Java?
- How to Retrieve Multiple Result Sets from a Stored Procedure in JDBC?
- What are local variables in Java?
- How to Use Updatable ResultSet in JDBC?
- How to Use JDBC Java to Create Table?
- Why final variable in Enhanced for Loop does not act final?