简体   繁体   中英

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:

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.

Now, I have a child class, 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.

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?

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() ). This goes back to the class Object itself. This way when you construct an object you intentionally (or not if you don't write super()) call the constructors of all super classes.

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. I hope I explained it properly ;)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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