Question:
A Simple Question about Java??
?
2012-08-29 09:22:30 UTC
I learnt in C++ that static functions can access static data members, But in java the "main()" method is static, But still it can access a non static member. Why is it???
Please explain.............
Four answers:
Ari
2012-08-29 09:33:19 UTC
in C++ and java, the word "static" is a little different.



in C++, a static variable is one that belongs to a class, instead of a particular object. I'm not sure there is a such thing as a static function in C++. (At least I've never used it).



a static method in java is a method that belongs to a class, and not a particular object. the main() method is static in java, since you the main() method isn't called on a specific object.



for example, in java the math library is really a class called Math. you can't even create an object of type Math, because Math is a static class. all of the methods are called as Math.method(parameters...)



let's say you write an application in java. you called it Hello.java.



first you compile it by writing "javac Hello.java" from the command line.



then to run it, you write "java Hello". the program called java, runs your .class file. Somehow, it knows to call main. it doesn't first do Hello h = new Hello(); then h.main(). it does the equivalent of Hello.main(); , meaning it calls main on the class, not any particular object.
Jon T
2012-08-29 16:44:13 UTC
Could you please provide an example where you are accessing a non-static member from within the public static void main(String [] args) method? Java is the same as C++ in that you cannot access non-static methods and variables from within a static method.



A static method/variable does not belong to an instance of an Object but rather to the Class itself. It can be accessed outside of the instantiation of a Class. A non-static variable/method can only be accessed by an instantiated Object, prior to the object being constructed those fields do not exist; therefore, they cannot be accessed by a static reference.
Sameer
2012-08-30 21:20:39 UTC
You misunderstood. we can not use non static variable in static method even in main also.



public static void main(String[] args) {

i=10;

System.out.println("\\");

}

private int i=0;



this code will give "Cannot make a static reference to the non-static field i" until you do not change it to static. But you can use non static variable that are declared inside static method like



public static void main(String[] args) {

int i=10;

System.out.println("\\");

}

with no error. You can visit my site if you like my answer androidtrainningcenter.blogspot.in
green meklar
2012-08-30 10:06:31 UTC
Static methods cannot reference LOCAL nonstatic variables or methods. However, they are perfectly free to explicitly access nonstatic variables and methods of specified objects. This is true in both C++ and Java.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...