构造函数是静态的或非静态的 [英] Constructor is static or non static

查看:119
本文介绍了构造函数是静态的或非静态的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据标准书构造函数是一种特殊类型的函数,用于初始化对象。构造函数被定义为函数,而类函数内部只能有两种类型的静态或非静态。我怀疑构造函数是什么?

As per standard book constructor is a special type of function which is used to initialize objects.As constructor is defined as a function and inside class function can have only two type either static or non static.My doubt is what constructor is ?

1.)As constructor is called without object so it must be static

  Test test =new  Test();//Test() is being called without object
   so must be static

我的疑问是,如果构造函数是静态方法,那么我们如何经常在
构造函数中使用它

My doubt is if constructor is static method then how can we frequently used this inside constructor

Test(){
System.out.println(this);
}

将给出测试@ 12aw212意味着这必须是非静态的...详细说明

Will give Test@12aw212 means this must be non static..Kindly elaborate

推荐答案

你的第二个例子击中了现场。 这个引用在构造函数中可用,这意味着构造函数是针对某个对象执行的 - 当前正在创建的对象。

Your second example hits the spot. this reference is available in the constructor, which means constructor is executed against some object - the one that is currently being created.

原则上,当您创建一个新对象(通过使用 new 运算符)时,JVM将为其分配一些内存,然后在该新创建的对象上调用构造函数。此外,JVM确保在构造函数之前没有调用其他方法(这就是它的特殊之处)。

In principle when you create a new object (by using new operator), JVM will allocate some memory for it and then call a constructor on that newly created object. Also JVM makes sure that no other method is called before the constructor (that's what makes it special).

实际上,在机器级别上,构造函数是一个特殊的函数,隐式参数。此特殊参数(由运行时传递)使对象和静态方法之间存在差异。换句话说:

Actually, on machine level, constructor is a function with one special, implicit this parameter. This special parameter (passed by the runtime) makes the difference between object and static methods. In other words:

foo.bar(42);

被翻译为:

bar(foo, 42);

其中第一个参数名为 this 。另一方面, static 方法按原样调用:

where first parameter is named this. On the other hand static methods are called as-is:

Foo.bar(42);

转换为:

bar(42);

Foo 这里只是一个现存的命名空间在源代码中。

Foo here is just a namespace existing barely in the source code.

这篇关于构造函数是静态的或非静态的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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