[英]Why do you not have to create an object in Java?
I'm learning Java and one of the things that suprised me is you don't create an object from a class. 我正在学习Java,令我惊讶的事情之一是您没有从类中创建对象。 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? 是否创建了从隐式运行main
方法的对象? 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. “类作为对象的蓝图”是描述现实的Java 101方法。 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. 在您的示例中, main
方法本身就是这样的静态方法,可以在不存在任何现有对象的情况下执行,而System.out
指的是一个单独存在的对象,该对象附加到System
类中的静态变量。
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. 如果在Java中仅使用静态方法和变量,则该类的所有对象都共享相同的变量和方法,则不必创建对象并调用。 Also the main method is the entry point for the code to run 同样,主要方法是代码运行的入口点
You do create objects in java. 您确实在Java中创建了对象。 The static keyword shows that the variable, method or nested class belongs to the class/superclass, and not to an object. static关键字表明变量,方法或嵌套类属于类/超类,而不属于对象。 The main method is declared static so that it can be accessed at runtime; main方法被声明为静态方法,因此可以在运行时进行访问; it is not part of an object, it is part of the class. 它不是对象的一部分,而是类的一部分。 The JVM looks for the main method at runtime. JVM在运行时查找main方法。
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 静态意味着你不必创建对象或其他文字没有需要的new
和你要求什么
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.