super() in constructor

怎甘沉沦 提交于 2019-12-17 18:03:21

问题


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();
}

回答1:


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)




回答2:


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




回答3:


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.




回答4:


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.



来源:https://stackoverflow.com/questions/15206890/super-in-constructor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!