我认为用适当的方法abstract
为你上一堂课可能会有所帮助。例如:objectType
getter/setter
public abstract class ParentObject {
private double hSpeed;
private double vSpeed;
/** Getter/setter methods */
public double gethSpeed() {
return hSpeed;
}
public void sethSpeed(double hSpeed) {
this.hSpeed = hSpeed;
}
public double getvSpeed() {
return vSpeed;
}
public void setvSpeed(double vSpeed) {
this.vSpeed = vSpeed;
}
}
然后,您可以对ObjectType
此类extend
进行具体实现ParentObject
。你会改变你的setPlayerFriction()
方法如下:
public void setPlayerFriction(ParentObject objectType, double hspeed, double vspeed){
double hSpeed = objectType.gethSpeed();
if(hSpeed >= GameWindow.friction){
objectType.sethSpeed(hSpeed - GameWindow.friction);
}else if(hSpeed <= -GameWindow.friction){
objectType.sethSpeed(hSpeed + GameWindow.friction);
}else{
objectType.sethSpeed(0);
}
double vSpeed = getvSpeed();
if(vSpeed >= GameWindow.friction){
objectType.setvSpeed(vSpeed - GameWindow.friction);
}else if(obj.vspeed <= -GameWindow.friction){
objectType.setvSpeed(vSpeed + GameWindow.friction);
}else{
objectType.setvSpeed(0);
}
}
对于这种方法,您基本上会发送实际上扩展了您的ParentObject
类的类的引用。例如:
public class ObjImpl extends ParentObject{
//Concrete implementation
}
public class ObjImpl2 extends ParentObject{
//Concrete implementation
}
public class TestClass{
public void setPlayerFriction(ParentObject objectType, double hspeed, double vspeed){
double hSpeed = objectType.gethSpeed();
if(hSpeed >= GameWindow.friction){
objectType.sethSpeed(hSpeed - GameWindow.friction);
}else if(hSpeed <= -GameWindow.friction){
objectType.sethSpeed(hSpeed + GameWindow.friction);
}else{
objectType.sethSpeed(0);
}
double vSpeed = getvSpeed();
if(vSpeed >= GameWindow.friction){
objectType.setvSpeed(vSpeed - GameWindow.friction);
}else if(obj.vspeed <= -GameWindow.friction){
objectType.setvSpeed(vSpeed + GameWindow.friction);
}else{
objectType.setvSpeed(0);
}
}
public static void main(String[] args) {
ParentObject object1 = new ObjImpl();
ParentObject object2 = new ObjImpl2();
setPlayerFriction(object1, 1.0d, 2.0d);
setPlayerFriction(object2, 2.25d, 2.0d);
}
}