I'm learning Java and one of the things that suprised me is you don't create an object from a class. For example:
class helloworld{
public static void main(String[] args){
System.out.println("Hello world!");
}
}
What I don't understand is that, I have always thought of a class as a blueprint for objects, whereas here you don't create an object and the program simply runs from the class. Is the creation of an object to run the main
method from implicit? I haven't exactly phrased this very well and assume that I am missing some piece of understanding - could someone explain?
"A class as a blueprint for objects" is a Java 101 way of describing the reality. It helps to teach you what classes and objects are, but it is not the whole truth.
A class is also a holder of static code and data, which exist on their own, independent of any class instances. You can view it as a kind of namespaced global data.
In your example, the main
method itself is such a static method, which can be executed with no existing objects, and System.out
refers to an object which exists on its own, attached to a static variable in the System
class.
If you are using only static methods and variables in java then all the object of that class share the same variables and methods, you dont have to create an object and call. Also the main method is the entry point for the code to run
You do create objects in java. The static keyword shows that the variable, method or nested class belongs to the class/superclass, and not to an object. The main method is declared static so that it can be accessed at runtime; it is not part of an object, it is part of the class. The JVM looks for the main method at runtime.
public mean it can be access from any class static
static mean you don't have to create object or in other word no need of the new
and that what you are asking about
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.