Java中构造函数的目的?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19941825/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Purpose of a constructor in Java?
提问by gator
What is the purpose of a constructor? I've been learning Java in school and it seems to me like a constructor is largely redundant in things we've done thus far. It remains to be seen if a purpose comes about, but so far it seems meaningless to me. For example, what is the difference between the following two snippets of code?
构造函数的目的是什么?我一直在学校学习 Java,在我看来,构造函数在我们迄今为止所做的事情中基本上是多余的。目的是否实现还有待观察,但到目前为止对我来说似乎毫无意义。例如,以下两段代码有什么区别?
public class Program {
public constructor () {
function();
}
private void function () {
//do stuff
}
public static void main(String[] args) {
constructor a = new constructor();
}
}
This is how we were taught do to things for assignments, but wouldn't the below do the same deal?
这就是我们被教导如何处理作业的方式,但下面的内容不会做同样的事情吗?
public class Program {
public static void main(String[] args) {
function();
}
private void function() {
//do stuff
}
}
The purpose of a constructor escapes me, but then again everything we've done thus far has been extremely rudimentary.
构造函数的目的让我无法理解,但是我们迄今为止所做的一切都非常简陋。
采纳答案by LotusUNSW
Constructors are used to initialize the instances of your classes. You use a constructor to create new objects often with parameters specifying the initial state or other important information about the object
构造函数用于初始化类的实例。您使用构造函数创建新对象,通常使用指定初始状态或有关对象的其他重要信息的参数
From the official Java tutorial:
来自官方 Java 教程:
A class contains constructorsthat are invoked to create objects from the class blueprint. Constructor declarations look like method declarations—except that they use the name of the class and have no return type. For example, Bicycle has one constructor:
public Bicycle(int startCadence, int startSpeed, int startGear) { gear = startGear; cadence = startCadence; speed = startSpeed; }
To create a new Bicycle object called
myBike
, a constructor is called by the new operator:Bicycle myBike = new Bicycle(30, 0, 8);
new Bicycle(30, 0, 8)
creates space in memory for the object and initializes its fields.Although Bicycle only has one constructor, it could have others, including a no-argument constructor:
public Bicycle() { gear = 1; cadence = 10; speed = 0; }
Bicycle yourBike = new Bicycle();
invokes the no-argument constructor to create a new Bicycle object called yourBike.
一类包含构造函数被调用,以创建类蓝图对象。构造函数声明看起来像方法声明——除了它们使用类的名称并且没有返回类型。例如,自行车有一个构造函数:
public Bicycle(int startCadence, int startSpeed, int startGear) { gear = startGear; cadence = startCadence; speed = startSpeed; }
要创建一个名为 的新 Bicycle 对象
myBike
,new 运算符会调用一个构造函数:自行车 myBike = 新自行车(30, 0, 8);
new Bicycle(30, 0, 8)
在内存中为对象创建空间并初始化其字段。尽管 Bicycle 只有一个构造函数,但它可以有其他构造函数,包括无参数构造函数:
公共自行车(){齿轮= 1;节奏= 10; 速度 = 0; }
Bicycle yourBike = new Bicycle();
调用无参数构造函数来创建一个名为 yourBike 的新 Bicycle 对象。
回答by Sam
- Through a constructor (with parameters), you can 'ask' the user of that class for required dependencies.
- It is used to initialize instance variables
- and to pass up arguments to the constructor of a super class (
super(...)
), which basically does the same - It can initialize (final) instance variables with code, that may throw Exceptions, as opposed to instance initializerscopes
- One should notblindly call methods from within the constructor, because initialization may not be finished/sufficient in the local or a derived class.
- 通过构造函数(带参数),您可以“询问”该类的用户所需的依赖项。
- 用于初始化实例变量
- 并将参数传递给超类 (
super(...)
)的构造函数,这基本上是相同的 - 它可以用代码初始化(最终)实例变量,这可能会抛出异常,而不是实例初始化范围
- 每个人都应该不盲目地叫从构造方法中的方法,因为初始化可能无法在本地或派生类中完成/充分。
回答by andy.xyz
It's used to set up the contents and state of your class. Whilst it's true you can make the simpler example with the main method you only have 1 main method per app so it does not remain a sensible approach.
它用于设置类的内容和状态。虽然确实可以使用 main 方法制作更简单的示例,但每个应用程序只有 1 个 main 方法,因此它仍然不是一种明智的方法。
Consider the main method to simply start your program and should know no more than how to do that. Also note that main() is static so cannot call functions that require a class instance and the state associated. The main method should call new Program().function() and the Program constructor should not call function() unless it is required for the setup of the class.
考虑简单地启动你的程序的主要方法,应该只知道如何做。另请注意, main() 是静态的,因此无法调用需要类实例和关联状态的函数。main 方法应该调用 new Program().function() 并且 Program 构造函数不应该调用 function() 除非它是设置类所必需的。
回答by Akira
A constructor is basically a method that you can use to ensure that objects of your class are born valid. This is the main motivation for a constructor.
构造函数基本上是一种方法,您可以使用它来确保类的对象天生有效。这是构造函数的主要动机。
Let's say you want your class has a single integer field that should be always larger than zero. How do you do that in a way that is reliable?
假设您希望您的类有一个应始终大于零的整数字段。你如何以一种可靠的方式做到这一点?
public class C {
private int number;
public C(int number) {
setNumber(number);
}
public void setNumber(int number) {
if (number < 1) {
throws IllegalArgumentException("C cannot store anything smaller than 1");
}
this.number = number;
}
}
In the code above, it may look like you are doing something redundant, but in fact you are ensuring that the number is always valid no matter what.
在上面的代码中,您可能看起来像是在做一些多余的事情,但实际上您正在确保无论如何该数字始终有效。
"initialize the instances of a class" is whata constructor does, but not the reason whywe have constructors. The question is about the purpose of a constructor. You can also initialize instances of a class externally, using c.setNumber(10)
in the example above. So a constructor is not the only way to initialize instances.
“初始化类的实例”是什么一个构造函数,但不是这个原因,为什么我们有构造函数。问题是关于构造函数的目的。您还可以使用c.setNumber(10)
上面的示例在外部初始化类的实例。所以构造函数并不是初始化实例的唯一方法。
The constructor does that but in a way that is safe. In other words, a class alone solves the whole problem of ensuring their objects are always in valid states. Not using a constructor will leave such validation to the outside world, which is bad design.
构造函数这样做,但以一种安全的方式。换句话说,一个类本身就解决了确保其对象始终处于有效状态的整个问题。不使用构造函数会将这种验证留给外界,这是糟糕的设计。
Here is another example:
这是另一个例子:
public class Interval {
private long start;
private long end;
public Interval(long start, long end) {
changeInterval(start, end);
}
public void changeInterval(long start, long end) {
if (start >= end) {
throw new IllegalArgumentException("Invalid interval.");
}
this.start = start;
this.end = end;
}
public long duration() {
return end - start;
}
}
The Interval class represents a time interval. Time is stored using long. It does not make any sense to have an interval that ends before it starts. By using a constructor like the one above it is impossible to have an instance of Interval at any given moment anywhere in the system that stores an interval that does not make sense.
Interval 类表示时间间隔。时间使用 long 存储。间隔在开始之前结束是没有任何意义的。通过使用像上面那样的构造函数,不可能在系统中的任何给定时刻都有一个 Interval 实例来存储一个没有意义的间隔。
回答by Prateek
As mentioned in LotusUNSW answer Constructors are used to initialize the instances of a class.
正如 LotusUNSW 回答中提到的,构造函数用于初始化类的实例。
Example:
例子:
Say you have an Animal
class something like
假设你有一个Animal
类似的课程
class Animal{
private String name;
private String type;
}
Lets see what happens when you try to create an instance of Animal class, say a Dog
named Puppy
. Now you have have to initialize name = Puppy
and type = Dog
. So, how can you do that. A way of doing it is having a constructor like
让我们看看当你尝试创建一个 Animal 类的实例时会发生什么,比如一个Dog
命名的Puppy
. 现在你必须初始化name = Puppy
和type = Dog
。那么,你怎么能做到这一点。一种方法是拥有一个构造函数,如
Animal(String nameProvided, String typeProvided){
this.name = nameProvided;
this.type = typeProvided;
}
Now when you create an object of class Animal
, something like Animal dog = new Animal("Puppy", "Dog");
your constructor is called and initializes name and type to the values you provided i.e. Puppy and Dog respectively.
现在,当您创建 class 的对象时Animal
,Animal dog = new Animal("Puppy", "Dog");
会调用类似于您的构造函数的东西,并将 name 和 type 分别初始化为您提供的值,即 Puppy 和 Dog。
Now you might ask what if I didn't provide an argument to my constructor something like
现在你可能会问如果我没有为我的构造函数提供一个参数会怎样
Animal xyz = new Animal();
This is a default Constructor
which initializes the object with default values i.e. in our Animal
class name
and type
values corresponding to xyz
object would be name = null
and type = null
这是一个default Constructor
用默认值初始化对象,即在我们的Animal
类中name
,type
对应于xyz
对象的值将是name = null
和type = null
回答by Vidya
The class definition defines the API for your class. In other words, it is a blueprint that defines the contract that exists between the class and its clients--all the other code that uses this class. The contract indicates which methods are available, how to call them, and what to expect in return.
类定义为您的类定义 API。换句话说,它是一个蓝图,它定义了类与其客户端之间存在的契约——所有其他使用这个类的代码。契约指明了哪些方法可用、如何调用它们以及期望得到什么回报。
But the class definition is a spec. Until you have an actual object of this class, the contract is just "a piece of paper." This is where the constructor comes in.
但是类定义是一个规范。在您拥有此类的实际对象之前,合同只是“一张纸”。这就是构造函数的用武之地。
A constructor is the means of creating an instance of your class by creating an object in memory and returning a reference to it. Something that shouldhappen in the constructor is that the object is in a proper initial state for the subsequent operations on the object to make sense.
构造函数是通过在内存中创建对象并返回对它的引用来创建类实例的方法。在构造函数中应该发生的事情是对象处于适当的初始状态,以便对对象进行后续操作。
This object returned from the constructor will now honor the contract specified in the class definition, and you can use this object to do real work.
从构造函数返回的这个对象现在将遵守类定义中指定的契约,您可以使用这个对象来做实际的工作。
Think of it this way. If you ever look at the Porsche website, you will see what it can do--the horsepower, the torque, etc. But it isn't fun until you have an actual Porsche to drive.
这么想吧。如果您查看过保时捷的网站,您就会看到它的功能——马力、扭矩等。但是,除非您拥有一辆真正的保时捷来驾驶,否则它并不有趣。
Hope that helps.
希望有帮助。
回答by Praveen Srinivasan
Constructor is basicaly used for initialising the variables at the time of creation of object
构造函数基本上用于在创建对象时初始化变量
回答by Naresh Kumar
A Java constructor has the same name as the name of the class to which it belongs.
Java 构造函数的名称与其所属的类的名称相同。
Constructor's syntax does not include a return type, since constructors never return a value.
构造函数的语法不包括返回类型,因为构造函数从不返回值。
Constructor is always called when object is created. example:- Default constructor
构造函数总是在创建对象时被调用。示例:- 默认构造函数
class Student3{
int id;
String name;
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student3 s1=new Student3();
Student3 s2=new Student3();
s1.display();
s2.display();
}
}
Output:
输出:
0 null
0 null
Explanation: In the above class,you are not creating any constructor so compiler provides you a default constructor.Here 0 and null values are provided by default constructor.
说明:在上面的类中,您没有创建任何构造函数,因此编译器为您提供了一个默认构造函数。这里 0 和 null 值由默认构造函数提供。
Example of parameterized constructor
参数化构造函数示例
In this example, we have created the constructor of Student class that have two parameters. We can have any number of parameters in the constructor.
在此示例中,我们创建了具有两个参数的 Student 类的构造函数。我们可以在构造函数中有任意数量的参数。
class Student4{
int id;
String name;
Student4(int i,String n){
id = i;
name = n;
}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
s1.display();
s2.display();
}
}
Output:
输出:
111 Karan
222 Aryan
回答by Ashish Thapa
A constructor initializes an object when it is created . It has the same name as its class and is syntactically similar to a method , but constructor have no expicit return type.Typically , we use constructor to give initial value to the instance variables defined by the class , or to perform any other startup procedures required to make a fully formed object.
构造函数在创建对象时对其进行初始化。它与它的类同名,在语法上与方法相似,但构造函数没有明确的返回类型。通常,我们使用构造函数为类定义的实例变量赋予初始值,或者执行生成完整对象所需的任何其他启动过程。
Here is an example of constructor:
下面是一个构造函数的例子:
class queen(){
int beauty;
queen(){
beauty = 98;
}
}
class constructor demo{
public static void main(String[] args){
queen arth = new queen();
queen y = new queen();
System.out.println(arth.beauty+" "+y.beauty);
}
}
output is:
输出是:
98 98
Here the construcor is :
这里的构造函数是:
queen(){
beauty =98;
}
Now the turn of parameterized constructor.
现在轮到参数化构造函数了。
class queen(){
int beauty;
queen(int x){
beauty = x;
}
}
class constructor demo{
public static void main(String[] args){
queen arth = new queen(100);
queen y = new queen(98);
System.out.println(arth.beauty+" "+y.beauty);
}
}
output is:
输出是:
100 98
回答by user6646964
I thought a constructor might work like a database in which only it defines variables and methods to control them
我认为构造函数可能像一个数据库一样工作,其中只有它定义变量和方法来控制它们
Then I saw objects that use variables and methods not defined in its constructor. So the discussion that makes the most sense to me is the one that tests variables values for validity, but the class can create variables and methods that are not defined in the constructor - less like a database and more like an over pressure valve on a steam locomotive. It doesn't control the wheels,etc.
然后我看到了使用未在其构造函数中定义的变量和方法的对象。所以对我来说最有意义的讨论是测试变量值的有效性,但该类可以创建未在构造函数中定义的变量和方法 - 不像数据库,更像是蒸汽上的过压阀机车。它不控制车轮等。
Far less of a definition than I thought.
远没有我想象的定义。