我有一个子类来处理拖到屏幕上的图像。它将每个图像的名称和x,y位置存储在变量中。然后它有一个方法来缩放它们并进行其他操作。
我想有2个这样的类,但图像名称和x,y位置会有所不同。
我首先尝试创建一个将此类作为子类的类。在这个父类中,我尝试创建相同的变量,希望它使用这些变量,而不是在子类中创建的变量。
子类仍然使用在其中创建的变量,而不是在父级中。
有没有办法做到这一点,还是我爬错了树?
public class cShapeParent extends cShapes {
// would like the base class to use this data
String[] mNames=
{
"ball_green.png",
"ball_green.png",
"ball_green.png"
};
cShapeParent(Context context,int screenWidth, int screenHeight)
{
super(context, screenWidth, screenHeight);
}
}
儿童班
import java.io.IOException;
import java.io.InputStream;
import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Rect;
public class cShapes {
public
String[] mNames=
{
"ball_green.png",
"ball_red.png",
"ball_blue.png"
};
int[] mX={200,300,400};
int[] mY={200,200,200};
int[] mW={0,0,0};
int[] mH={0,0,0};
int Amount=3;
int MyScreenWidth=512;
int[] BitMapId={
R.drawable.ball_green, R.drawable.ball_red,
R.drawable.ball_blue, R.drawable.ball_green
};
Bitmap MyImages[];
Rect[] mBitmapSize;
cShapes(Context context,int screenWidth, int screenHeight)
{
// Load in bitmaps
MyImages=new Bitmap[4];
AssetManager assetManager= context.getAssets();
InputStream inputStream;
mBitmapSize = new Rect[Amount];
try {
// set scaling ratio
float r=(float)MyScreenWidth / (float)screenWidth;
for(int i=0;i<Amount;i++)
{
inputStream=assetManager.open( mNames[i]);
MyImages[i]=BitmapFactory.decodeStream(inputStream);
int w=(int)( (float)MyImages[i].getWidth()*r);
int h=(int)( (float)MyImages[i].getWidth()*r);
mBitmapSize[i]=new Rect(0,0,w,h);
mW[i]=w; mH[i]=h;
mX[i]=(int) ( (float)mX[i]*r);
mY[i]=(int) ( (float)mY[i]*r);
inputStream.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
boolean Intersect(int id, int x,int y)
{
if ( x >= mX[id] && x <= mX[id]+128 && y >= mY[id] && y <= mY[id]+128 )
return true;
return false;
}
} // end class
答案 0 :(得分:1)
如果我正确理解你的问题,你想要从子类中访问超类中定义的变量。如果那是你的问题,那么可以使用超级关键字。
class Super{
public int i;
}
class Sub extends Super {
public void method() {
System.out.println(super.i); // you can access i as it is overriden by sub
}
}
请注意,即使没有超级关键字,您也可以直接访问i
,我只是将其包含在内以使其更具表现力。但是,如果未将其声明为i
,则只能访问此示例中的private
。
答案 1 :(得分:0)
等等,您是否希望Child(cShapeParent
)类创建并保留Parent(cShapes
)类可以引用的变量?在这种情况下,我会遵循这种模式:
public class Child extends Parent {
private String[] mNames= {
"ball_green.png",
"ball_red.png",
"ball_blue.png"
};
protected String[] getNames() {
return mNames;
}
}
public abstract class Parent {
protected abstract ListString[] getNames();
public void doX() {
...
String[] names = getNames();
...
}
}