为什么要写公共静态 [英] why to write Public static

查看:92
本文介绍了为什么要写公共静态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么要编写Public static void main(),如果我不写static,将会发生什么事情?

Why to write Public static void main(), if i don''t write static what will happen??

推荐答案

静态方法没有实例.它们用类型名而不是实例标识符来调用.因此,它们比实例方法要快一些.静态方法可以是公共的或私有的.他们不能使用此实例表达式.
Static methods have no instances. They are called with the type name, not an instance identifier. They are slightly faster than instance methods because of this. Static methods can be public or private. They cannot use the this instance expression.


它将引发错误,因为静态main是程序的入口点.
由于类中的静态函数使用类名直接调用,例如

课程计划
{
静态void main(){}

void main2();
}

主要功能将称为Program.Main();

main2函数将需要一个由程序类构成的对象,然后将其调用.该函数将为所有对象提供单独的引用,其中静态函数是单个的,并且对于所有对象的完整类都是通用的.
这就是为什么需要具有静态函数main的原因,该函数由编译器在内部通过类名称进行调用.
It will throw an error, because, static main is the entry point for a program.
As static functions in a class are called direct with the class name, like for example

class Program
{
static void main(){}

void main2();
}

Main function will be called as Program.Main();

And main2 function will require an object to be made of program class and then it will called. This function will have a separate reference for all the objects, where as static functions are single and common for the complete class for all objects.
That is why it is require to have static function main, which is internally called by the compiler by the class name.


当类成员被声明为静态成员时,可以在任何其他成员之前访问它将创建该类的对象,并且不引用任何对象.方法和变量都可以声明为静态.最好的例子是我们的main(),它被声明为静态的.它是静态的,因为必须在任何对象存在之前调用它.
When a class member is declared as static, it can be accessed before any object of that class is created and without reference to any object. Both methods and variable can be declared as static. The best example to understand is our main() which is declared static. Its is static because it must be called before any object exist.


这篇关于为什么要写公共静态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆