简体   繁体   English

Java:如何在子类构造函数中调用超类构造函数?

[英]Java: How does a call to the super class constructor inside of a child class constructor work?

I'm just trying to get my head around this.我只是想弄清楚这个。 Let's say I have the following constructor for the superclass Geometry:假设我有以下超类 Geometry 的构造函数:

public Geometry(double x, double y)
    {
        this.position = new Point(x,y);
        this.collisionMesh = new ArrayList<Point>();
        this.displayMesh = new ArrayList<Point>();
    }

Geometry has the members position, collisionMesh, and displayMesh, which all of its child classes will inherit. Geometry 具有成员 position、collisionMesh 和 displayMesh,其所有子类都将继承这些成员。

Now, I have a child class, Particle.现在,我有一个子类 Particle。 Is the following a valid constructor:以下是有效的构造函数:

public Particle(double x, double y)
{
   super(x,y);
   this.collisionMesh.add(this.position);
   ...
}

What I want to make sure of is this: the call to super(x,y) automatically instantiates my child object's ArrayLists and Point, so that I don't need to do so.我想确保的是:对 super(x,y) 的调用会自动实例化我的子对象的 ArrayLists 和 Point,因此我不需要这样做。

Also, on a deeper level, and assuming I can do this, what's really going on here?此外,在更深层次上,假设我可以做到这一点,这里到底发生了什么? It feels like I'm calling a constructor inside of a constructor.感觉就像我在构造函数内部调用构造函数。 What is it that gets constructed during the call to super, if the Particle object isn't done being constructed yet?如果 Particle 对象尚未构建完成,那么在调用 super 期间构建的是什么?

To generate the object you need to call the constructors of the super class.要生成对象,您需要调用超类的构造函数。 It must be on the first line of your constructor.它必须在构造函数的第一行。 If you don't add that line java automatically calls the super class constructor without arguments (like there is an invsible super() ).如果您不添加该行,java 将自动调用不带参数的超类构造函数(就像有一个 invsible super() )。 This goes back to the class Object itself.这可以追溯到类 Object 本身。 This way when you construct an object you intentionally (or not if you don't write super()) call the constructors of all super classes.这样,当您构造一个对象时,您有意(或者如果您不编写 super() 则不会)调用所有超类的构造函数。

If the super class doesn't have no arguments constructor you get a compile error in the subclass if you don't call the super constructor with proper arguments (because this cannot work automatically).如果超类没有无参数构造函数,如果您不使用正确的参数调用超构造函数(因为这不能自动工作),您将在子类中得到编译错误。

When you create a type Particle it first creates an Object, then extends that object to a Geometry and then to a Particle.创建类型 Particle 时,它​​首先创建一个 Object,然后将该对象扩展为 Geometry,然后扩展为 Particle。 I hope I explained it properly ;)我希望我能正确解释它;)

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

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