为什么这个类中的三个构造函数中有两个使用 this(context) 而不是 super(context)?
该类(class)是一个更大项目的一部分,可在 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();
}
}
最佳答案
在构造函数中,this()
做的事情与 super()
不同。调用 this()
推迟到同一类中的重载构造函数。调用 super()
调用父类(super class)构造函数。
在这里,前两个 TouchExampleView
构造函数调用 this
以通过传递默认值来推迟到第三个构造函数。第三个构造函数调用 super
来调用父类(super class)构造函数(加上做一些其他事情)。
Java Language Specification, Section 8.8.7.1描述了这些调用。
Explicit constructor invocation statements can be divided into two kinds:
Alternate constructor invocations begin with the keyword this (possibly prefaced with explicit type arguments). They are used to invoke an alternate constructor of the same class.
Superclass constructor invocations begin with either the keyword super (possibly prefaced with explicit type arguments) or a Primary expression. They are used to invoke a constructor of the direct superclass.
关于java - 为什么这个类中的某些构造函数使用 this(context) 而不是 super(context)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16576045/