1

为什么这个类的三个构造函数中有两个使用 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();
    }
}

}

4

1 回答 1

3

在构造函数中,this()做一些不同于super(). 调用this()延迟到同一类中的重载构造函数。调用super()调用超类构造函数。

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

Java 语言规范第8.8.7.1 节描述了这些调用。

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

备用构造函数调用以关键字 this 开头(可能以显式类型参数开头)。它们用于调用同一类的备用构造函数。

超类构造函数调用以关键字 super(可能以显式类型参数开头)或 Primary 表达式开头。它们用于调用直接超类的构造函数。

于 2013-05-15T22:29:20.783 回答