gpt4 book ai didi

java - 他们是让子类使用父类中创建的变量的一种方法吗?

转载 作者:行者123 更新时间:2023-12-01 15:02:04 26 4
gpt4 key购买 nike

我有一个子类来处理拖到屏幕上的图像。它将每个图像的名称以及 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

最佳答案

如果我正确理解你的问题,你想从你的子类访问你的父类(super class)中定义的变量。如果这就是您的问题,那么是的,可以使用 super 关键字。

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
}
}

请注意,即使没有 super 关键字,您也可以直接访问 i,我只是将其包含在内以使其更具表现力。但是,在此示例中,当 i 未声明为 private 时,您只能访问它。

关于java - 他们是让子类使用父类中创建的变量的一种方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13503283/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com