Nazerke
Nazerke

Reputation: 2098

super() in constructor

I'm reading through some code. In the constructor it has super() but the class implements interface which of course doesn't have a constructor. So which super() it is referring to?

public class BoundingBox implements IBoundingVolume {

public BoundingBox() {
        super();
        mTransformedMin = new Number3D();
        mTransformedMax = new Number3D();
        mTmpMin = new Number3D();
        mTmpMax = new Number3D();
        mPoints = new Number3D[8];
        mTmp = new Number3D[8];
        mMin = new Number3D();
        mMax = new Number3D();
        for(int i=0; i<8; ++i) {
            mPoints[i] = new Number3D();
            mTmp[i] = new Number3D();
        }
}


public interface IBoundingVolume {
    public void calculateBounds(Geometry3D geometry);
    public void drawBoundingVolume(Camera camera, float[] projMatrix, float[] vMatrix, float[] mMatrix);
    public void transform(float[] matrix);
    public boolean intersectsWith(IBoundingVolume boundingVolume);
    public BaseObject3D getVisual();
}

Upvotes: 30

Views: 76687

Answers (4)

disha
disha

Reputation: 1

Now let me tell you the real reason why we use super() here that is if we want to call directly super-class constructor . when we call constructor then many constructor may be invoked in hierarchy,so to eliminate that we can use super(). During test-cases you might deal with "Do not provide any additional constructor other than what is asked in the problem statement" so, The solution is use Super() in your constructor.

Upvotes: -1

Zach Latta
Zach Latta

Reputation: 3331

super calls the constructor of the extended class. All classes in Java derive from Object. Additionally, if the author of a class doesn't create a constructor for the class, a default constructor is created that does nothing.

In your case, super is calling the default constructor of Object.

If you'd like to learn more about Object, you can read the source code of Object.java here.

Upvotes: 4

jfmg
jfmg

Reputation: 2666

Super is referencing to the extended class. By default it is the Object class. The constructor in Object does nothing. In other words you can delete this line as it is not necessary.

Please also note what Oracle is saying about this topic:

If a constructor does not explicitly invoke a superclass constructor, the Java compiler automatically inserts a call to the no-argument constructor of the superclass. If the super class does not have a no-argument constructor, you will get a compile-time error. Object does have such a constructor, so if Object is the only superclass, there is no problem.

Source: http://docs.oracle.com/javase/tutorial/java/IandI/super.html

Upvotes: 19

cowls
cowls

Reputation: 24334

super() refers to the extended class (not an implemented interface). Which in this case is Object

So it will call the constructor in Object (Which does nothing)

Upvotes: 46

Related Questions