为什么这个类中的一些构造函数使用this(context)而不是super(context)?

时间:2013-05-15 22:28:06

标签: java android oop

为什么这个类中的三个构造函数中有两个使用this(context)而不是super(context)?

该课程是https://code.google.com/p/android-touchexample/source/browse/branches/cupcake/src/com/example/android/touchexample/TouchExampleView.java

提供的大型项目的一部分
package com.example.android.touchexample;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

public class TouchExampleView extends View {

private Drawable mIcon;
private float mPosX;
private float mPosY;

private VersionedGestureDetector mDetector;
private float mScaleFactor = 1.f;

public TouchExampleView(Context context) {
    this(context, null, 0);
}

public TouchExampleView(Context context, AttributeSet attrs) {
    this(context, attrs, 0);
}

public TouchExampleView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    mIcon = context.getResources().getDrawable(R.drawable.icon);
    mIcon.setBounds(0, 0, mIcon.getIntrinsicWidth(), mIcon.getIntrinsicHeight());

    mDetector = VersionedGestureDetector.newInstance(context, new GestureCallback());
}

@Override
public boolean onTouchEvent(MotionEvent ev) {
    mDetector.onTouchEvent(ev);
    return true;
}

@Override
public void onDraw(Canvas canvas) {
    super.onDraw(canvas);

    canvas.save();
    canvas.translate(mPosX, mPosY);
    canvas.scale(mScaleFactor, mScaleFactor);
    mIcon.draw(canvas);
    canvas.restore();
}

private class GestureCallback implements VersionedGestureDetector.OnGestureListener {
    public void onDrag(float dx, float dy) {
        mPosX += dx;
        mPosY += dy;
        invalidate();
    }

    public void onScale(float scaleFactor) {
        mScaleFactor *= scaleFactor;

        // Don't let the object get too small or too large.
        mScaleFactor = Math.max(0.1f, Math.min(mScaleFactor, 5.0f));

        invalidate();
    }
}

}

1 个答案:

答案 0 :(得分:3)

在构造函数中,this()执行与super()不同的操作。调用this()会延迟到同一个类中的重载构造函数。调用super()会调用超类构造函数。

这里,前两个TouchExampleView构造函数通过传递默认值来调用this来推迟第三个构造函数。第三个构造函数调用super来调用超类构造函数(再做一些其他的事情)。

Java Language Specification, Section 8.8.7.1描述了这些电话。

  

显式构造函数调用语句可以分为两种:

     

备用构造函数调用以关键字this开头   (可能以显式类型参数开头)。他们习惯了   调用同一个类的替代构造函数。

     

超类构造函数调用以关键字super开头   (可能以显式类型参数开头)或主要版本   表达。它们用于调用direct的构造函数   超类。

相关问题