java 在java中创建构造函数的额外好处是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17721316/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-01 14:46:43  来源:igfitidea点击:

what is the extra benefit of creating constructor in java?

javamethodsconstructor

提问by Tushar Monirul

I have noticed a thing that a constructor and a simple method of a class do the same work. what is the exact reason to create a construct of a class? If i create MyClass(){}constructor and MyClassMethod(){}method it will do the same work as I write the body part of those method and constructor. So what is the need of construct? Does it have any special use ?

我注意到一个构造函数和一个类的简单方法做同样的工作。创建类的构造的确切原因是什么?如果我创建MyClass(){}构造函数和MyClassMethod(){}方法,它将完成与我编写这些方法和构造函数的主体部分相同的工作。那么构建的必要性是什么?它有什么特殊用途吗?

回答by c.s.

A constructor and a method are two different things. The fact that you can write the same or similar code inside them is irrelevant.

构造函数和方法是两种不同的东西。您可以在其中编写相同或相似的代码这一事实无关紧要。

When a new object is created a constructor is called. If you don't specify one the compiler will create a default one for you. This is the place where initializaton of the object's fields takes place and memory is allocated for the object. This is a concept that all object-oriented languages have. A new object must be initialized somehow. Memory needs to be allocated. In Java you don't manage the memory yourself (at least not directly anyway) so this is the purpose of the constructor. Note that since a constructor is always executed, this behaviour is enforcedas soon as you call e.g. Person p = new Person();.

创建新对象时,会调用构造函数。如果您不指定一个,编译器将为您创建一个默认的。这是对象字段初始化和为对象分配内存的地方。这是所有面向对象语言都有的概念。必须以某种方式初始化新对象。需要分配内存。在 Java 中,您自己不管理内存(至少不是直接管理),因此这是构造函数的目的。请注意,由于始终执行构造函数,因此只要您调用 eg 就会强制执行此行为Person p = new Person();

Now since a constructor is always being called, you have an option here: do you let the default constructor execute or do you create one yourself? Perhaps there are fields that need to be initialized in a way other than their default values. Or perhaps you need to not allow creating an object without providing some values. If you define a constructor yourself, the compiler does not create a default one for you. So if I have public Person(String firstName, String lastName) {}then I have created a specific rule that is again enforced by the system: a new object of class Person cannot be created unless you give a first name and last name:

现在,由于总是调用构造函数,您在这里有一个选择:是让默认构造函数执行还是自己创建一个?也许有些字段需要以默认值以外的方式进行初始化。或者您可能需要不允许在不提供某些值的情况下创建对象。如果您自己定义构造函数,编译器不会为您创建默认构造函数。因此,如果我已经public Person(String firstName, String lastName) {}创建了一个由系统再次强制执行的特定规则:除非您提供名字和姓氏,否则无法创建类 Person 的新对象:

Person p = new Person(); // this would give a compile error
Person p = new Person("John", "Smith"); // this is the only way to create an object now

Using a method you cannot enforce this. The programmer using your class might call your method or not. The constructor is a part of the lifecycleof the object. Methods define the behaviourof the object

使用您无法强制执行此操作的方法。使用您的类的程序员可能会调用或不调用您的方法。构造函数是对象生命周期的一部分。方法定义对象的行为

回答by NINCOMPOOP

Some points :

几点:

1) Constructors are the only way to set finalinstance variables .

1) 构造函数是设置final实例变量的唯一方法。

public class SomeType {
   final int x ;
   SomeType(int y){
     x=y;
   }
}

2) A class with privateconstructor cannot be sub classed.

2) 带有private构造函数的类不能被子类化。

3) If your class is a subclass and the base class doesn't have a default constructor , then you need a constructor in your class to call the super class constructor.

3)如果您的类是子类并且基类没有默认构造函数,那么您的类中需要一个构造函数来调用超类构造函数。

回答by Kevin Bowersox

One of the benefits of using a constructor over a method is that you can be assured the constructor was called and the work within the constructor was performed.

使用构造函数而不是方法的好处之一是可以确保调用构造函数并执行构造函数中的工作。

The language specifies that to construct an object a constructor must be called. So if you use a custom method to establish the initial state of your object, you will need to call the default constructor first. Why make two method calls when you can perform the work in one call the constructor and be assured the object has been properly initialized?

该语言指定要构造对象必须调用构造函数。因此,如果您使用自定义方法来建立对象的初始状态,则需要先调用默认构造函数。当您可以在一次调用构造函数中执行工作并确保对象已正确初始化时,为什么要进行两次方法调用?

public class Test(){

    private Integer x;

    public Test(){

    }

    public Test(Integer x){
       this.x = x;
    }

    public void setX(Integer x){
       this.x = x;
    }

    public void doSomethingWithX(){
       this.x.toString();
    }
}

Test test = new Test(8);
test.doSomethingWithX(); //I know x has been declared and assigned

Test test = new Test();
test.doSomethingWithX(); //X has not been assigned results in NPE

回答by Benjamin Schwalb

If you create a new Object of MyClassit will automatically call the constructor - you can initialize all members within it, and be sure that this object′s members are all initialized.

如果你创建一个新的对象,MyClass它会自动调用构造函数——你可以初始化其中的所有成员,并确保该对象的成员都已初始化。

Generally:
A constructor is alwayscalled oncewhen you create a new Object of this class, and you can′tcall it manually.
And don′tdo "real" work in a constructor, as it will slow down the creation of objects of this class - only initialize your class/members there.

一般:创建该类的新对象时,
构造函数总是被调用一次不能手动调用。
并且不要在构造函数中做“真正的”工作,因为它会减慢此类对象的创建速度 - 仅在那里初始化您的类/成员。

You can also use different constructors, depending on your needs - but if you create a constructor, there is no more default constructor!

您还可以根据需要使用不同的构造函数——但是如果您创建了一个构造函数,就没有更多的默认构造函数了!

Example:

例子:

public MyClass {

   int score;

   public MyClass(int sc) { // already know the score
    score = sc;
   }

   public MyClass() { // don′t know the score yet
    score = 1;
   }

   public void addScore() {
   score += 5;   // i know for sure that score is not zero 
   }

}

回答by robjohncox

Essentially a constructor is just a special method that implicitly returns an object of its containing type. You should generally use constructors for creating objects - this is what people expect to see.

本质上,构造函数只是一个特殊的方法,它隐式返回其包含类型的对象。您通常应该使用构造函数来创建对象——这是人们期望看到的。

However, there is a useful idiom called the factory method(more info at this link) which is essentially using a static method to construct an object, the key advantages being

然而,有一个有用的习语叫做factory method(更多信息在这个链接),它本质上是使用静态方法来构造一个对象,主要优点是

  • You can give a factory method a more descriptive name (whereas of course a standard constructor has to be named after the containing class).
  • They don't haveto return an object, giving more flexibility.
  • They can return a sub-types of the class.
  • 您可以为工厂方法指定一个更具描述性的名称(而标准构造函数当然必须以包含类的名称命名)。
  • 他们不具备返回一个对象,提供更大的灵活性。
  • 它们可以返回类的子类型。

回答by Zain Zafar

Constructor is not like simple methods. It is called every time when the object of that particular class is created. You don't need to call it explicitly.

构造函数不像简单的方法。每次创建该特定类的对象时都会调用它。您不需要显式调用它。



There are somethings that we need to do immediately when the object is created, for instance when you create a GUI kind of thing you want to set many properties on the time of creation like size of window etc. Another benefit of constructor is security of class. You cannot create a object unless you know the right perimeters of constructor.

在创建对象时,我们需要立即做一些事情,例如,当您创建 GUI 类型的事情时,您希望在创建时设置许多属性,例如窗口大小等。构造函数的另一个好处是类的安全性. 除非您知道构造函数的正确周长,否则您无法创建对象。



More details:http://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html

更多详情:http: //docs.oracle.com/javase/tutorial/java/javaOO/constructors.html

回答by rashedcs

A constructor is a special method of a class or structure in object-oriented programming that initializes an object of that type.

构造函数是面向对象编程中类或结构的特殊方法,用于初始化该类型的对象。

Some points :

几点:

1. A constructor eliminates placing the default values.
2. A constructor eliminates calling the normal method implicitly.

回答by Beryllium

You can set finalfields without initializer in a constructor. This helps to build immutableinstances:

您可以final在构造函数中设置没有初始值设定项的字段。这有助于构建immutable实例:

class Number extends Expr {
    private final int n;

    public Number(int n) {
        this.n = n;
    }

    public int getValue() {
        return this.n;
    }
}

So after a constructor like this, you can rely on the fact that the instance is initialized completely(and in this case, it's values are immutable/constant).

因此,在这样的构造函数之后,您可以依赖实例已完全初始化的事实(在这种情况下,它的值是不可变的/常量)。