java构造函数_Java构造函数
java构造函数
Constructor in java is used to create the instance of the class. Constructors are almost similar to methods except for two things – its name is the same as the class name and it has no return type. Sometimes constructors are also referred to as special methods to initialize an object.
java中的构造⽅法⽤于创建类的实例。 构造函数⼏乎与⽅法类似,除了两点:其名称与类名称相同,并且没有返回类型。 有时,构造函数也称为初始化对象的特殊⽅法。
Java构造函数 (Constructor in Java)
Whenever we use new keyword to create an instance of a class, the constructor is invoked and the object of the class is returned. Since constructor can only return the object to class, it’s implicitly done by java runtime and we are not supposed to add a return type to it.
每当我们使⽤new关键字创建类的实例时,就会调⽤构造函数并返回该类的对象。 由于构造函数只能将对象返回给类,因此它是由Java运⾏时隐式完成的,我们不应该向其添加返回类型。
If we add a return type to a constructor, then it will become a method of the class. This is the way java runtime distinguish between a normal method and a constructor. Let’s assume we have following code in Employee class.
如果我们向构造函数添加返回类型,则它将成为该类的⽅法。 这是Java运⾏时区分普通⽅法和构造函数的⽅式。 假设在Employee类中有以下代码。
public Employee() {
System.out.println("Employee Constructor");
}
public Employee Employee() {
System.out.println("Employee Method");
return new Employee();
}
Here the first one is a constructor, notice that there is no return type and no return statement. The second one is a normal method where we are again calling the first constructor to get Employee instance and return it. It’s recommended to not have method name same as the class name because it creates confusion.
这⾥的第⼀个是构造函数,请注意没有返回类型也没有return语句。 第⼆个是普通⽅法,我们再次调⽤第⼀个构造函数来获取Employee实例并返回它。 建议不要使⽤与类名相同的⽅法名,因为这会造成混乱。
Java构造函数的类型 (Types of Constructor in Java)
There are three types of constructor in java.
Java中有三种构造函数。
1. Default Constructor
默认构造函数
2. No-Args constructor
⽆参数构造函数
3. Parameterized constructor
参数化构造函数
Let’s look into all these constructor types with example programs.
让我们⽤⽰例程序研究所有这些构造函数类型。
Java中的默认构造函数 (Default Constructor in Java)
It’s not required to always provide a constructor implementation in the class code. If we don’t provide a constructor, then java provides default constructor implementation for us to use. Let’s look at a simple program where default constructor is being used since we will not explicitly define a constructor.
不需要总是在类代码中提供构造函数实现。 如果我们不提供构造函数,那么java将提供默认的构造函数实现供我们使⽤。 让我们看⼀个使⽤默认构造函数的简单程序,因为我们不会显式定义构造函数。
package structor;
public class Data {
public static void main(String[] args) {
Data d = new Data();
}
}
1. Default constructor only role is to initialize the object and return it to the calling code.
默认构造函数的唯⼀作⽤是初始化对象并将其返回给调⽤代码。
2. Default constructor is always without argument and provided by java compiler only when there is no existing
constructor defined.
默认构造函数始终没有参数,并且仅当没有定义现有构造函数时才由Java编译器提供。
构造函数可以被重载3. Most of the time we are fine with default constructor itself as other properties can be accessed and initialized through
getter setter methods.
在⼤多数情况下,我们可以使⽤默认构造函数本⾝,因为可以通过getter setter⽅法访问和初始化其他属性。
⽆Args构造函数 (No-Args Constructor)
Constructor without any argument is called a no-args constructor. It’s like overriding the default constructor and used to do some pre-initialization stuff such as checking resources, network connections, logging, etc. Let’s have a quick look at the no-args constructor in java.
没有任何参数的构造函数称为⽆参数构造函数。 这就像覆盖默认构造函数,并⽤于执⾏⼀些预初始化的⼯作,例如检查资源,⽹络连接,⽇志记录等。让我们快速了解⼀下Java中的no-args构造函数。
package structor;
public class Data {
//no-args constructor
public Data() {
System.out.println("No-Args Constructor");
}
public static void main(String[] args) {
Data d = new Data();
}
}
Now when we will call new Data(), then our no-args constructor will be called. Below image illustrates this behavior, check the console output of the program.
现在,当我们调⽤new Data()时,将调⽤我们的⽆参数构造函数。 下图说明了此⾏为,请检查程序的控制台输出。
参数化构造函数 (Parameterized Constructor)
Constructor with arguments is called parameterized constructor. Let’s look at the example of parameterized constructor in java.
带参数的构造函数称为参数化构造函数。 让我们看⼀下Java中参数化构造函数的⽰例。
package structor;
public class Data {
private String name;
public Data(String n) {
System.out.println("Parameterized Constructor");
this.name = n;
}
public String getName() {
return name;
}
public static void main(String[] args) {
Data d = new Data("Java");
System.out.Name());
}
}
Java中的构造⽅法重载 (Constructor Overloading in Java)
When we have more than one constructors, then it’s constructor overloading in java. Let’s look at an example of constructor overloading in java program.
当我们有多个构造函数时,则是Java中的构造函数重载。 让我们来看⼀个Java程序中构造函数重载的⽰例。
package structor;
public class Data {
private String name;
private int id;
//no-args constructor
public Data() {
this.name = "Default Name";
}
//one parameter constructor
public Data(String n) {
this.name = n;
}
//two parameter constructor
public Data(String n, int i) {
this.name = n;
this.id = i;
}
public String getName() {
return name;
}
public int getId() {
return id;
}
@Override
public String toString() {
return "ID="+id+", Name="+name;
}
public static void main(String[] args) {
Data d = new Data();
System.out.println(d);
d = new Data("Java");
System.out.println(d);
d = new Data("Pankaj", 25);
System.out.println(d);
}
}
Java的私有构造函数 (Private Constructor in Java)
Note that we can’t use , final, and synchronized keywords with constructors. However we can use access modifiers to control the instantiation of class object. Using public and default access is still fine, but what is the use of making a constructor private? In that case any other class won’t be able to create the instance of the class.
注意,我们不能在构造函数中使⽤ ,final, 和sync关键字。 但是,我们可以使⽤访问修饰符来控制类对象的实例化。 使
⽤public和default访问仍然可以,但是将构造函数设为私有有什么⽤? 在这种情况下,任何其他类都将⽆法创建该类的实例。
Well, a constructor is made private in case we want to implement . Since java automatically provides d
efault constructor, we have to explicitly create a constructor and keep it private. Client classes are provided with a utility static method to get the instance of the class. An example of private constructor for Data class is given below.
好吧,如果我们要实现 ,可以将构造函数设为私有。 由于java⾃动提供了默认的构造函数,因此我们必须显式创建⼀个构造函数并将其保持私有状态。 客户端类提供了实⽤程序静态⽅法来获取该类的实例。 下⾯给出了Data类的私有构造函数⽰例。
// private constructor
private Data() {
//empty constructor for singleton pattern implementation
//can have code to be used inside the getInstance() method of class
}
Java中的构造函数链接 (Constructor Chaining in Java)
When a constructor calls another constructor of the same class, it’s called constructor chaining. We have to use this keyword to call another constructor of the class. Sometimes it’s used to set some default values of the class variables.
当⼀个构造函数调⽤同⼀类的另⼀个构造函数时,称为构造函数链接。 我们必须使⽤this关键字来调⽤该类的另⼀个构造函数。 有时,它⽤于设置类变量的⼀些默认值。
Note that another constructor call should be the first statement in the code block. Also, there should not be recursive calls that will create an infinite loop. Let’s see an example of constructor chaining in java program.
注意,另⼀个构造函数调⽤应该是代码块中的第⼀条语句。 另外,不应有会创建⽆限循环的递归调⽤。 让我们看⼀下Java程序中构造函数链接的⽰例。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。