2015-03-25 69 views
2

在Java中,类的构造函数是否创建该类的实例?如果是这样,它是否也初始化该类的变量?Java构造函数和初始化类变量

+3

不,构造函数不会创建实例。构造函数初始化一个实例。 – 2015-03-25 02:46:45

+0

谢谢!我尝试阅读文档,但对我而言并不清楚。你碰巧知道了解构造函数的基础知识的任何好的来源吗? – andrejon 2015-03-25 02:47:54

+0

@SotiriosDelimanolis创建和初始化有什么区别? – yitzih 2015-03-25 03:06:31

回答

0

构造函数不创建对象。它们只是在使用参数(提供时)或默认值创建对象(及其数据成员)时才初始化对象(及其数据成员)。

0

当您使用new运算符创建类的实例时,将调用该类的构造函数以初始化实例变量。 如果定义的构造函数是默认构造函数,则必须将实例变量显式指定给新创建的对象。 但是,如果使用字段覆盖构造函数,则会在创建对象时分配该新创建对象的实例变量。

1
Constructor doesn’t create the instance of the Class. 

Instance creation is done using either: 

    1.Using Class.forName() 

    2.ClassLoader loadClass() 

    3.Using clone() 

    4.Deserialization 

    5.Using reflection 

    6.new keyword 


Constructor in java is a special type of method that is used to initialize the object. 

Java constructor is invoked at the time of object creation. It constructs the values i.e. provides data for the object that is why it is known as constructor. 

Rules for creating java constructor 

There are basically two rules defined for the constructor. 

     1.Constructor name must be same as its class name 

     2.Constructor must have no explicit return type 

Types of java constructors 

There are two types of constructors: 

    1.Default constructor (no-arg constructor) 

    2.Parameterized constructor 
相关问题