简体   繁体   English

Java中的对象初始值设定项和构造函数有什么区别?

[英]what is the difference between an object initializer and a constructor in java?

正如我研究过的那样,构造函数用于创建类对象和初始化实例字段。但是在抽象类中,当子类继承抽象类并创建子类的对象时也会创建构造函数。根据抽象类的定义,我们无法创建因此,如何在不创建抽象类对象的情况下调用抽象类的构造函数。

创建子类时,您必须调用超类构造函数。

I'm not sure how well this answers your question, but in my experience I've only used abstract constructors to call a super() in the subclass constructors. 我不确定这能否很好地回答您的问题,但是根据我的经验,我仅使用抽象构造函数在子类构造函数中调用super() I can't say Parent x = new Parent(); 我不能说Parent x = new Parent(); but I can say Parent y = new Child() where the first line of Child() is super(); 但我可以说Parent y = new Child()其中的第一行Child()super(); , essentially calling Parent(); ,实质上是调用Parent(); .

We can not create the object of abstract class but we can create the constructor of abstract class and we can call it in sub class using super() 我们不能创建抽象类的对象,但可以创建抽象类的构造函数,并且可以使用super()在子类中调用它

abstract class abc{
  abc(){}

}
class Test extends abc{
super();
}

A contructor intialize the instance of the fields and give them default values if they dont have any value at the time of intialization 构造器初始化这些字段的实例,并在初始化时不赋予它们默认值的情况下为它们提供默认值

class A{
  int b;
}
A a = new A();
System.out.println("value of b "+b);

answer is : value of b 0

the constructor intialize the fileds with default values 构造函数使用默认值初始化文件

By using super() you can call constructor of abstract class from its sub class. 通过使用super()您可以从其子类中调用抽象类的构造函数。 For eg. 例如。 your abstract class have fields a and b and you want to initialize those so this can be done from its sub class by using abstract class constructor and super() . 您的abstract class具有ab字段,并且您希望对其进行初始化,因此可以通过使用abstract class constructorsuper()从其sub class完成此操作。

I think the best answer is in the first comment. 我认为最好的答案是在第一条评论中。 You don't actually use the constructor in this case to instantiate the abstract class but to initialize its state and the invariants. 在这种情况下,您实际上并不使用构造函数来实例化抽象类,而是初始化其状态和不变量。 Let's say you were allowed to create a subclass without calling super(...), there would be cases where you'd have a partially constructed object 假设您被允许在不调用super(...)的情况下创建子类,在某些情况下,您将拥有部分构造的对象

public abstract class AbstractMe {
    protected List<Object> objects;
    protected AbstractMe() { 
         objects = new ArrayList<>();
    }
    protected int elements() { return objects.size(); }
}

If you call super elements will always work fine, but if you were allowed not to call it it could be a NPE even if your invariant is that there always is a list in your class. 如果您调用超级元素,则始终可以正常工作,但是,如果您不被允许调用它,则即使您的不变之处是您的班级中始终存在一个列表,它也可能是NPE。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM