简体   繁体   中英

Abstract class to instantiate another implemented abstract class

So I'm trying to make a game using LibGDX so my codes kind of messy, so I'll simplify it here. Basically I have an abstract class Weapon, and and Abstract class Bullet. Within the weapon class, there should be a field for a type of Bullet. How can I go about this? This is so that the shooting method can create an instance of the correct bullet.

Also if I was to create a static list within the abstract Bullet class and add each instance to it, would this work? or would it change for each different implemented Bullet?

public abstract class Weapon {
    public Bullet bullet;
}

public abstract class Bullet { 
    public Vector2 position;
    public Bullet(Vector2 position){
        this.position = position;
    }
}

public Rifle extends Weapon{
    this.bullet = RifleBullet.class;
}

public RifleBullet extends Bullet{
    public RifleBullet(Vector2 start){ 
        super(start);   
    }    
}

I do recommend avoiding inheritance wherever possible. It just makes your life easier. Instead, do something like this:

public class Weapon {
   private final Bullet template;

   public Weapon(Bullet template) {
      this.template = template;
   }
   /* shoot logic here */
}

public class Bullet { 
   private final Vector2 position;
   private final float velocity;
   public Bullet(float speed) {
      this.position = new Vector2();
      this.speed = speed;
   }
   /* setters and getters */
}

This follows the Composition over Inheritance principle, which allows you to keep your code simple and gives you more control:

Bullet rifleBullet = new Bullet(2f);
Weapon rifle = new Weapon(rifleBullet);

Bullet shotgunBullet = new Bullet(5f);
Weapon shotgun = new Weapon(shotgunBullet);

/* somewhere in update() */
shotgun.shoot();
rifle.shoot();

The shoot() method then could implement the creation of actual bullets (eg using libgdx bullets ). This separates your logical model from the actual physics or render code. Make sure to add more arguments to the weapon constructor to describe what makes your weapon different or unique from other weapons. This information then can be used within the shoot() method fire a bullet with the attributes provided.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM